Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

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

    
26
import org.apache.commons.lang.StringUtils;
27
import org.apache.log4j.Logger;
28
import org.eclipse.jface.preference.IPreferenceStore;
29
import org.eclipse.jface.window.Window;
30
import org.eclipse.swt.widgets.Composite;
31
import org.eclipse.swt.widgets.Control;
32
import org.eclipse.swt.widgets.Shell;
33
import org.eclipse.ui.PlatformUI;
34

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

    
67
/**
68
 * <p>
69
 * PreferencesUtil class.
70
 * </p>
71
 *
72
 * @author p.ciardelli
73
 * @author n.hoffmann
74
 * @created 05.12.2008
75
 * @version 1.0
76
 */
77
public class PreferencesUtil implements IPreferenceKeys {
78

    
79
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
80

    
81
	private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
82

    
83
	/**
84
	 * <p>
85
	 * getPreferenceStore
86
	 * </p>
87
	 *
88
	 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
89
	 */
90
	public static IPreferenceStore getPreferenceStore() {
91
		return TaxeditorStorePlugin.getDefault().getPreferenceStore();
92
	}
93

    
94
	/**
95
	 * <p>
96
	 * setPreferredNomenclaturalCode
97
	 * </p>
98
	 *
99
	 * @param preferredCode
100
	 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
101
	 *            object.
102
	 */
103
	public static CdmPreference setPreferredNomenclaturalCode(
104
			String preferenceKey, boolean local) {
105
	    if (local){
106
	        getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
107
	                preferenceKey);
108
	    }
109
	    else{
110
    		ICdmRepository controller;
111
    		controller = CdmStore.getCurrentApplicationConfiguration();
112
    		PrefKey key = null;
113
    		try{
114
    		    key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
115
    		}catch (Exception e){
116
    		    System.out.println(e.getStackTrace());
117
    		}
118
    		CdmPreference preference = null;
119
    		if (controller == null){
120
    			return null;
121
    		}
122
    		if (preferenceKey == null){
123
    			preference = controller.getPreferenceService().find(key);
124
    			if (preference == null){
125
    				return null;
126
    			} else{
127
//    				int index = StringUtils.lastIndexOf(preference.getValue(), ".");
128
//    				UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
129
//    				preferredCode = NomenclaturalCode.getByUuid(uuid);
130

    
131
    				getPreferenceStore().setValue(CDM_NOMENCLATURAL_CODE_KEY,
132
    				        preferenceKey);
133
    				getPreferenceStore().setValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY,preference.isAllowOverride());
134
    				return preference;
135
    			}
136
    		} else{
137
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceKey);
138
    			controller.getPreferenceService().set(preference);
139

    
140
    		}
141
	    }
142
        return null;
143

    
144

    
145

    
146
	}
147

    
148
	public static NomenclaturalCode getPreferredNomenclaturalCode(){
149
	    if (getPreferenceStore().getBoolean(OVERRIDE_NOMENCLATURAL_CODE_KEY)) {
150
            return getPreferredNomenclaturalCode(true);
151
        } else{
152
            return getPreferredNomenclaturalCode(false);
153
        }
154
	}
155

    
156
	/**
157
	 * <p>
158
	 * getPreferredNomenclaturalCode
159
	 * </p>
160
	 *
161
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
162
	 */
163
	public static NomenclaturalCode getPreferredNomenclaturalCode(boolean useLocal) {
164

    
165
		CdmPreference pref = null;
166
		if (!useLocal){
167
		    pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
168
		}
169

    
170
	    String preferredCode;
171
	    if(pref == null){
172
	    	preferredCode = getPreferenceStore().getString(
173
					PREFERRED_NOMENCLATURAL_CODE_KEY);
174

    
175
	    }else{
176
	    	preferredCode = pref.getValue();
177
	    }
178

    
179
	    return getPreferredNomenclaturalCode(preferredCode);
180

    
181
	}
182

    
183
	/**
184
     * <p>
185
     * getPreferredNomenclaturalCode
186
     * </p>
187
     *
188
     * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
189
     */
190
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
191

    
192
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
193
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
194
                return code;
195
            }
196
        }
197
        return null;
198
    }
199

    
200
	public static boolean isShowTaxonAssociations(){
201
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
202
            return getPreferenceStore().getBoolean(SHOW_TAXON_ASSOCIATIONS);
203
        } else{
204
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowTaxonAssociations);
205

    
206
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
207
        }
208
    }
209

    
210
	public static boolean isShowLifeForm(){
211
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
212
            return getPreferenceStore().getBoolean(SHOW_LIFE_FORM);
213
        } else{
214
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowLifeForm);
215

    
216
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
217
        }
218
    }
219

    
220
	public static boolean isDeterminationOnlyForFieldUnits(){
221
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
222
            return getPreferenceStore().getBoolean(DETERMINATION_ONLY_FOR_FIELD_UNITS);
223
        } else{
224
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.DeterminationOnlyForFieldUnits);
225

    
226
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
227
        }
228
    }
229

    
230
	public static boolean isCollectingAreaInGeneralSection(){
231
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
232
            return getPreferenceStore().getBoolean(SHOW_COLLECTING_AREAS_IN_GENERAL_SECTION);
233
        } else{
234
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowCollectingAreasInGeneralSection);
235

    
236
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
237
        }
238
    }
239

    
240
	public static boolean isShowSimpleDetailsView(){
241
        if (getPreferenceStore().getBoolean(OVERRIDE_NAME_DETAILS) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_NAME_DETAILS)) {
242
            return getPreferenceStore().getBoolean(SHOW_SIMPLE_NAME_DETAILS_SECTION);
243
        } else{
244
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
245

    
246
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
247
        }
248
    }
249

    
250

    
251

    
252
    public static CdmPreference getPreferenceFromDB(PreferencePredicate predicate){
253
        ICdmRepository controller;
254
        CdmPreference pref = null;
255

    
256
        try{
257
            if(CdmStore.isActive()){
258
                controller = CdmStore.getCurrentApplicationConfiguration();
259
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), predicate);
260
                pref = controller.getPreferenceService().find(key);
261
            }
262
        }catch(Exception e){
263
            e.printStackTrace();
264
        }
265

    
266
        return pref;
267

    
268
    }
269

    
270
    public static void setPreferenceToDB(CdmPreference preference){
271
        ICdmRepository controller;
272
        try{
273
            if(CdmStore.isActive()){
274
                controller = CdmStore.getCurrentApplicationConfiguration();
275
                controller.getPreferenceService().set(preference);
276
            }
277
        }catch(Exception e){
278
            e.printStackTrace();
279
        }
280

    
281
    }
282

    
283

    
284

    
285
	public static String getPreferredDefaultLangugae(){
286
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
287
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
288
	        return preferredLanguage;
289
	    }
290
	    return null;
291
	}
292

    
293
	public static boolean isShowMediaPreview(){
294
        boolean isShowMediaPreview = getPreferenceStore().getBoolean(SHOW_MEDIA_PREVIEW);
295
        return isShowMediaPreview;
296
    }
297

    
298
	/**
299
	 * Get the match strategy for the given class that was stored in preferences
300
	 * or the default strategy if it was not stored in preferences
301
	 *
302
	 * @param clazz
303
	 *            a {@link java.lang.Class} object.
304
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
305
	 */
306
	public static IMatchStrategy getMatchStrategy(Class clazz) {
307
		String className = clazz.getName();
308
		if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
309
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
310

    
311
			for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
312
				String matchModeName = getPreferenceStore().getString(
313
						getMatchStrategyFieldName(className, fieldName));
314
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
315
				try {
316
					matchStrategy.setMatchMode(fieldName, matchMode);
317
				} catch (MatchException e) {
318
					MessagingUtils.error(PreferencesUtil.class, e);
319
					throw new RuntimeException(e);
320
				}
321
			}
322

    
323
			return matchStrategy;
324
		}
325
		return getDefaultMatchStrategy(clazz);
326
	}
327

    
328
	/**
329
	 * Stores a matchStrategy into the preference store.
330
	 *
331
	 * @param matchStrategy
332
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
333
	 *            object.
334
	 */
335
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
336
		String className = matchStrategy.getMatchClass().getName();
337
		getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
338

    
339
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
340

    
341
		for (String fieldName : matchFields) {
342
			getPreferenceStore().setValue(
343
					getMatchStrategyFieldName(className, fieldName),
344
					matchStrategy.getMatchMode(fieldName).name());
345
		}
346
	}
347

    
348
	/**
349
	 * Helper method to create the preference property for a match field.
350
	 *
351
	 * @param className
352
	 * @param fieldName
353
	 * @return
354
	 */
355
	private static String getMatchStrategyFieldName(String className,
356
			String fieldName) {
357
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
358
	}
359

    
360
	/**
361
	 * Returns the default match strategy for a given class.
362
	 *
363
	 * @param clazz
364
	 *            a {@link java.lang.Class} object.
365
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
366
	 */
367
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
368
		return DefaultMatchStrategy.NewInstance(clazz);
369
	}
370

    
371
	/**
372
	 * <p>
373
	 * getDateFormatPattern
374
	 * </p>
375
	 *
376
	 * @return a {@link java.lang.String} object.
377
	 */
378
	public static String getDateFormatPattern() {
379
		// TODO make this configurable in properties
380
		String pattern = "Y-M-d H:m";
381
		return pattern;
382
	}
383

    
384
	/**
385
	 * <p>
386
	 * addTermToPreferredTerms
387
	 * </p>
388
	 *
389
	 * @param term
390
	 *            a T object.
391
	 * @param <T>
392
	 *            a T object.
393
	 */
394
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
395

    
396
		// VocabularyEnum vocabulary =
397
		// VocabularyEnum.getVocabularyEnum(term.getClass());
398
		//
399
		// getPreferenceStore().setValue(getPreferenceKey(term),
400
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
401
		//
402
		// firePreferencesChanged(term.getClass());
403
	}
404

    
405
	/**
406
	 * Construct a unique key using the CdmBase object's uuid
407
	 *
408
	 * @param cdmBase
409
	 * @return
410
	 */
411
	private static String getPreferenceKey(ICdmBase cdmBase) {
412
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
413

    
414
		String key = cdmBase.getClass().getName().concat(".")
415
				.concat(cdmBase.getUuid().toString());
416
		if (key.contains("javassist")) {
417
			MessagingUtils.info("proxy");
418
		}
419
		return key;
420
	}
421

    
422
	/**
423
	 * Construct a unique key using the CdmBase object's uuid
424
	 *
425
	 * @param cdmBase
426
	 * @return
427
	 */
428
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
429
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
430
		String key = simpleTerm.getClass().getName().concat(".")
431
				.concat(simpleTerm.getUuid().toString());
432
		if (key.contains("javassist")) {
433
			MessagingUtils.warn(PreferencesUtil.class,
434
					"Trying to persist a preference based on a proxy class.");
435
		}
436
		return key;
437
	}
438

    
439

    
440

    
441
	/**
442
	 * Construct a unique key using the CdmBase object's uuid
443
	 *
444
	 * @param cdmBase
445
	 * @return
446
	 */
447
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
448
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
449
		String key = definedTerm.getClass().getName().concat(".")
450
				.concat(definedTerm.getUuid().toString());
451
		if (key.contains("javassist")) {
452
			MessagingUtils.warn(PreferencesUtil.class,
453
					"Trying to persist a preference based on a proxy class.");
454
		}
455
		return key;
456
	}
457

    
458
	/**
459
	 * Retrieves search preferences from the preference store
460
	 *
461
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
462
	 */
463
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
464
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
465

    
466
		configurator.setDoTaxa(getPreferenceStore().getBoolean(
467
				TAXON_SERVICE_CONFIGURATOR_TAXA));
468
		configurator.setDoSynonyms(getPreferenceStore().getBoolean(
469
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
470
		configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
471
				TAXON_SERVICE_CONFIGURATOR_NAMES));
472
		configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
473
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
474
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getPreferenceStore().getString(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
475

    
476
		return configurator;
477
	}
478

    
479
	/**
480
	 * create new preferences, setting all search options to true
481
	 *
482
	 * @return a
483
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
484
	 *         object.
485
	 */
486
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
487
		IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
488

    
489
		configurator.setDoTaxa(true);
490
		configurator.setDoSynonyms(true);
491
		configurator.setDoNamesWithoutTaxa(true);
492
		configurator.setDoTaxaByCommonNames(true);
493

    
494
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
495
				"name", "name.$", "relationsFromThisTaxon.$"));
496

    
497
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
498
				"name", "name.$", "synonyms.relatedTo.*"));
499

    
500
		// DEFAULT VALUES
501
		// match mode is a simple like, actually all other match modes are kind
502
		// of bogus
503
		configurator
504
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
505
		// we set page number and size here as this should always be unlimited
506
		configurator.setPageNumber(0);
507
		// TODO currently limit results to 10000
508
		configurator.setPageSize(10000);
509

    
510
		return configurator;
511
	}
512

    
513
	/**
514
	 * Store search preferences
515
	 *
516
	 * @param configurator
517
	 *            a
518
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
519
	 *            object.
520
	 */
521
	public static void setSearchConfigurator(
522
			IFindTaxaAndNamesConfigurator configurator) {
523
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
524
				configurator.isDoTaxa());
525
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
526
				configurator.isDoSynonyms());
527
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
528
				configurator.isDoNamesWithoutTaxa());
529
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
530
				configurator.isDoTaxaByCommonNames());
531
	}
532

    
533
	/**
534
	 * <p>
535
	 * firePreferencesChanged
536
	 * </p>
537
	 *
538
	 * @param clazz
539
	 *            a {@link java.lang.Class} object.
540
	 */
541
	public static void firePreferencesChanged(Class clazz) {
542
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
543
				null, clazz);
544
	}
545

    
546
	/**
547
	 * Set default values for preferences
548
	 */
549
	public static void setDefaults() {
550
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
551
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
552
				true);
553
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
554
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
555
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
556
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
557
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
558
				"http://www.biodiversitylibrary.org/openurl");
559
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
560
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
561
		getPreferenceStore().setDefault(IPreferenceKeys.DISTRIBUTION_AREA_PREFRENCES_ACTIVE, false);
562
		getPreferenceStore().setDefault(CHECKLIST_ID_IN_VOCABULARY, true);
563
		getPreferenceStore().setDefault(CHECKLIST_SYMBOL, false);
564
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, true);
565
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE, true);
566
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, true);
567
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_HYBRID, true);
568
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_LSID, true);
569
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, true);
570
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAMECACHE, true);
571
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, true);
572
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, true);
573
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, true);
574
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, true);
575
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_RANK, true);
576
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, true);
577
		getPreferenceStore().setDefault(SORT_NODES_NATURALLY, false);
578
		getPreferenceStore().setDefault(SORT_NODES_ALPHABETICALLY, false);
579
		getPreferenceStore().setDefault(SORT_TAXA_BY_RANK_AND_NAME, true);
580

    
581
	}
582

    
583
	/**
584
	 * <p>
585
	 * checkNomenclaturalCode
586
	 * </p>
587
	 */
588
	public static void checkNomenclaturalCode() {
589
		// First time Editor is opened, no nomenclatural code has been set
590

    
591

    
592
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
593
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
594
		}
595

    
596

    
597

    
598
	}
599
	public static void setNomenclaturalCodePreferences(){
600
	    ICdmRepository controller;
601
        controller = CdmStore.getCurrentApplicationConfiguration();
602
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
603
        CdmPreference preference = null;
604
        if (controller == null){
605
            return ;
606
        }
607
        preference = controller.getPreferenceService().find(key);
608
        if (preference == null){
609
            return;
610
        }
611
        getPreferenceStore().setValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
612

    
613
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
614
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
615
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
616

    
617
        getPreferenceStore().setValue(CDM_NOMENCLATURAL_CODE_KEY,
618
                getPreferenceKey(preferredCode));
619

    
620
        if (!preference.isAllowOverride()){
621
            getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
622
                    getPreferenceKey(preferredCode));
623
        }
624
	}
625

    
626
	public static void checkDefaultLanguage(){
627
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
628
	       Shell shell = AbstractUtility.getShell();
629
	       int open = new DefaultLanguageDialog(shell).open();
630
	       if(open == Window.OK){
631
	           PlatformUI.getWorkbench().restart();
632
	       }
633
	    }else{
634
	        //TODO:In case of a reinstall, the config.ini will be overwritten
635
	        //     here you create config.ini with the stored key from preferences
636
	    }
637
	}
638

    
639
	/**
640
	 * <p>
641
	 * getMapServiceAccessPoint
642
	 * </p>
643
	 *
644
	 * @return a {@link java.lang.String} object.
645
	 */
646
	public static String getMapServiceAccessPoint() {
647
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
648
	}
649

    
650
	/**
651
	 * <p>
652
	 * shouldConnectAtStartUp
653
	 * </p>
654
	 *
655
	 * @return a boolean.
656
	 */
657
	public static boolean shouldConnectAtStartUp() {
658
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
659
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
660
		return false;
661
	}
662

    
663
	/**
664
	 * <p>
665
	 * getDefaultFeatureTreeForTextualDescription
666
	 * </p>
667
	 *
668
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
669
	 */
670
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
671
		String uuidString = getPreferenceStore().getString(
672
				FEATURE_TREE_DEFAULT_TEXT);
673
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
674
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
675
	}
676

    
677
	/**
678
	 * <p>
679
	 * getDefaultFeatureTreeForStructuredDescription
680
	 * </p>
681
	 *
682
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
683
	 */
684
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
685
		String uuidString = getPreferenceStore().getString(
686
				FEATURE_TREE_DEFAULT_STRUCTURE);
687
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
688
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
689
	}
690

    
691
	/**
692
	 * <p>
693
	 * setSortRanksHierarchichally
694
	 * </p>
695
	 *
696
	 * @param selection
697
	 *            a boolean.
698
	 */
699
	public static void setSortRanksHierarchichally(boolean selection) {
700
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
701
	}
702

    
703
	/**
704
	 * <p>
705
	 * getSortRanksHierarchichally
706
	 * </p>
707
	 *
708
	 * @return a boolean.
709
	 */
710
	public static boolean getSortRanksHierarchichally() {
711
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
712
	}
713

    
714
	public static boolean isMultilanguageTextEditingCapability() {
715
		return getPreferenceStore().getBoolean(
716
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
717
	}
718

    
719
	public static Language getGlobalLanguage() {
720

    
721

    
722
		String languageUuidString = getPreferenceStore().getString(
723
				GLOBAL_LANGUAGE_UUID);
724

    
725
		if(!CdmStore.isActive()) {
726
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
727
            return null;
728
        }
729

    
730
		if (CdmUtils.isBlank(languageUuidString)) {
731
			return Language.getDefaultLanguage();
732
		}
733

    
734
		UUID languageUuid = UUID.fromString(languageUuidString);
735
		return (Language) CdmStore.getService(ITermService.class).load(
736
				languageUuid);
737
	}
738

    
739
	public static void setGlobalLanguage(Language language) {
740
	    if(language != null) {
741
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
742
	        CdmStore.setDefaultLanguage(language);
743
	    }
744

    
745
	}
746

    
747
	/**
748
	 * @return
749
	 */
750
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
751
		List<MarkerType> markerTypes = CdmStore.getTermManager()
752
				.getPreferredTerms(MarkerType.class);
753

    
754
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
755

    
756
		for (MarkerType markerType : markerTypes) {
757
			String name = getMarkerTypeEditingPreferenceKey(markerType);
758
			Boolean value = getPreferenceStore().getBoolean(name);
759

    
760
			result.put(markerType, value);
761
		}
762

    
763
		return result;
764
	}
765

    
766
	/**
767
	 * @param markerTypeEditingMap
768
	 */
769
	public static void setEditMarkerTypePreferences(
770
			Map<MarkerType, Boolean> markerTypeEditingMap) {
771
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
772
			String name = getMarkerTypeEditingPreferenceKey(markerType);
773
			getPreferenceStore().setValue(name,
774
					markerTypeEditingMap.get(markerType));
775
		}
776

    
777
	}
778

    
779
	private static String getMarkerTypeEditingPreferenceKey(
780
			MarkerType markerType) {
781
		markerType = HibernateProxyHelper.deproxy(markerType);
782
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
783
	}
784

    
785
	/**
786
	 * <p>
787
	 * setEditMarkerTypePreference
788
	 * </p>
789
	 *
790
	 * @param input
791
	 *            a {@link org.eclipse.ui.IEditorInput} object.
792
	 * @param markerType
793
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
794
	 * @param edit
795
	 *            a boolean.
796
	 */
797
	public static void setEditMarkerTypePreference(MarkerType markerType,
798
			boolean edit) {
799
		getPreferenceStore().setValue(
800
				getMarkerTypeEditingPreferenceKey(markerType), edit);
801
	}
802

    
803
	/**
804
	 * @return
805
	 */
806
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
807
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
808
				.NewInstance();
809
		configurator.setMoveDerivedUnitMediaToGallery(true);
810
		configurator.setMoveFieldObjectMediaToGallery(true);
811
		return configurator;
812
	}
813

    
814
	/**
815
	 * This method will write language properties to the config.ini located in the configuration folder
816
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
817
	 *
818
	 * @param setLanguage 0 is for german and 1 for english.
819
	 * @throws IOException
820
	 */
821
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
822
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
823
        //give warning to user if the directory has no write access
824
        if(file == null){
825
            throw new IOException();
826
        }
827
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
828
        switch(setLanguage){
829
        case 0:
830
            properties.setProperty("osgi.nl", "de");
831
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
832
            break;
833
        case 1:
834
            properties.setProperty("osgi.nl", "en");
835
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
836
            break;
837
        default:
838
            break;
839
        }
840
        save(file+"/config.ini", properties);
841
    }
842

    
843
    /**
844
     * This method loads a property from a given file and returns it.
845
     *
846
     * @param filename
847
     * @return
848
     * @throws IOException
849
     */
850
    private Properties load(String filename) throws IOException {
851
        FileInputStream in = new FileInputStream(filename);
852
        Properties prop = new Properties();
853
        prop.load(in);
854
        in.close();
855
        return prop;
856
    }
857

    
858
    /**
859
     * This method saves a property to the specified file.
860
     *
861
     * @param filename
862
     * @param properties
863
     * @throws IOException
864
     */
865
    private void save(String filename, Properties properties) throws IOException{
866
        FileOutputStream fos =  new FileOutputStream(filename);
867
        properties.store(fos, "");
868
        fos.close();
869
    }
870

    
871

    
872
    /**
873
     * enables/disables nested composite. <br>
874
     *
875
     * @param ctrl - Composite to be en-/disabeld
876
     * @param enabled - boolean
877
     */
878
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
879
        if (ctrl instanceof Composite) {
880
            Composite comp = (Composite) ctrl;
881
            for (Control c : comp.getChildren()) {
882
                recursiveSetEnabled(c, enabled);
883
            }
884
        } else {
885
            ctrl.setEnabled(enabled);
886
        }
887
    }
888

    
889
    /**
890
	 * <p>
891
	 * getSortRanksNaturally
892
	 * </p>
893
    	 *
894
    	 * @return a boolean.
895
	 */
896
	public static boolean getSortNodesNaturally() {
897
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
898
	}
899

    
900
	/**
901
	 * <p>
902
	 * setSortRanksNaturally
903
	 * </p>
904
	 *
905
	 * @param selection
906
	 *            a boolean.
907
	 */
908
	public static void setSortNodesNaturally(boolean selection) {
909
		getPreferenceStore().setValue(SORT_NODES_NATURALLY, selection);
910
	}
911

    
912

    
913
	/**
914
	 * <p>
915
	 * getSortRanksNaturally
916
	 * </p>
917
	 *
918
	 * @return a boolean.
919
	 */
920
	public static boolean getSortNodesStrictlyAlphabetically() {
921
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
922
	}
923

    
924
	/**
925
	 * <p>
926
	 * setSortRanksNaturally
927
	 * </p>
928
	 *
929
	 * @param selection
930
	 *            a boolean.
931
	 */
932
	public static void setSortNodesStrictlyAlphabetically(boolean selection) {
933
		getPreferenceStore().setValue(SORT_NODES_ALPHABETICALLY, selection);
934
	}
935

    
936
	/**
937
	 * <p>
938
	 * setStoreNavigatorState
939
	 * </p>
940
	 *
941
	 * @param selection
942
	 *            a boolean.
943
	 */
944
	public static boolean isStoreNavigatorState() {
945
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
946

    
947
	}
948

    
949
	/**
950
	 * <p>
951
	 * setStoreNavigatorState
952
	 * </p>
953
	 *
954
	 * @param selection
955
	 *            a boolean.
956
	 */
957
	public static void setStoreNavigatorState(boolean selection) {
958
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
959

    
960
	}
961

    
962
    /**
963
     * @return
964
     */
965
    public static boolean isShowUpWidgetIsDisposedMessages() {
966
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
967
    }
968
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
969
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
970
    }
971

    
972
    /**
973
     * @return
974
     */
975
    public static boolean isShowIdInVocabularyInChecklistEditor() {
976
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
977
    }
978
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
979
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
980
    }
981

    
982
    /**
983
     * @return
984
     */
985
    public static boolean isShowSymbolInChecklistEditor() {
986
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SYMBOL);
987
    }
988
    public static void setShowSymbolInChecklistEditor(boolean selection) {
989
        getPreferenceStore().setValue(CHECKLIST_SYMBOL, selection);
990
    }
991

    
992
    /**
993
     * @return
994
     */
995
    public static boolean isShowRankInChecklistEditor() {
996
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
997
    }
998
    public static void setShowRankInChecklistEditor(boolean selection) {
999
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
1000
    }
1001

    
1002
    /**
1003
     * @param object
1004
     * @param b
1005
     * @return
1006
     */
1007
    public static NameDetailsConfigurator setPreferredNameDetailsConfiguration( boolean local) {
1008
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1009

    
1010
        CdmPreference preference = null;
1011

    
1012
        if (!local) {
1013
            preference = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1014
            if (preference == null){
1015
                return null;
1016
            }
1017

    
1018
            getPreferenceStore().setValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1019

    
1020
            //the preference value is build like this:
1021
            //<section1>:true;<section2>:false....
1022

    
1023
            String value = preference.getValue();
1024
            String [] sections = value.split(";");
1025
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1026
            String[] sectionValues;
1027
            for (String sectionValue: sections){
1028
                sectionValues = sectionValue.split(":");
1029
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1030
            }
1031
            config.setAllowOverride(preference.isAllowOverride());
1032
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1033

    
1034
    //        getPreferenceStore().setValue(SHOW_SIMPLE_NAME_DETAILS_TAXON,
1035
    //                (getValue(sectionMap, "taxon")));
1036
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1037

    
1038
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_LSID,
1039
    //                (getValue(sectionMap, "lsid")));
1040
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1041

    
1042
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1043
    //                (getValue(sectionMap, "nc")));
1044
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1045

    
1046
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1047
    //                (getValue(sectionMap, "ap")));
1048
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1049

    
1050
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_RANK,
1051
    //                (getValue(sectionMap, "rank")));
1052
            config.setRankActivated(getValue(sectionMap, "rank"));
1053

    
1054

    
1055
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1056
    //                (getValue(sectionMap, "atomisedEpithets")));
1057
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1058

    
1059
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1060
    //                (getValue(sectionMap,"author")));
1061
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1062

    
1063
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1064
    //                (getValue(sectionMap, "nomRef")));
1065
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1066

    
1067
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1068
    //                (getValue(sectionMap, "nomStat")));
1069
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1070

    
1071

    
1072
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1073
    //                (getValue(sectionMap,"protologue")));
1074
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1075

    
1076
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1077
    //                (getValue(sectionMap,"typeDes")));
1078
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1079

    
1080
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1081
    //                (getValue(sectionMap,"nameRelation")));
1082
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1083

    
1084
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_HYBRID,
1085
    //                (getValue(sectionMap, "hybrid")));
1086
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1087
        }else{
1088
            config.setSimpleDetailsViewActivated(getPreferenceStore().getBoolean(SHOW_SIMPLE_NAME_DETAILS_SECTION));
1089
            config.setTaxonSectionActivated(getPreferenceStore().getBoolean(SHOW_SIMPLE_NAME_DETAILS_TAXON));
1090
            config.setLSIDActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_LSID));
1091
            config.setNomenclaturalCodeActived(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1092
            config.setAppendedPhraseActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1093
            config.setRankActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_RANK));
1094
            config.setAtomisedEpithetsActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1095
            config.setAuthorshipSectionActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1096
            config.setNomenclaturalReferenceSectionActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1097
            config.setNomenclaturalStatusSectionActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1098
            config.setProtologueActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1099
            config.setTypeDesignationSectionActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1100
            config.setNameRelationsSectionActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1101
            config.setHybridActivated(getPreferenceStore().getBoolean(SHOW_NAME_DETAILS_SECTION_HYBRID));
1102
        }
1103
        return config;
1104
    }
1105

    
1106
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1107
		if (sectionMap.containsKey(string)){
1108
			return sectionMap.get(string);
1109
		}else{
1110
			return true;
1111
		}
1112

    
1113
	}
1114

    
1115

    
1116

    
1117
    /**
1118
     * <p>
1119
     * setAbcdConfigurator
1120
     * </p>
1121
     *
1122
     * @param preferredConfiguration
1123
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1124
     *            object.
1125
     */
1126
    public static Abcd206ImportConfigurator getAbcdImportConfigurationPreference(boolean useLocal) {
1127

    
1128
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1129

    
1130
        if (useLocal){
1131
            config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1132

    
1133
            config.setAddMediaAsMediaSpecimen(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1134

    
1135
            config.setAllowReuseOtherClassifications(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1136
            config.setDeduplicateClassifications(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1137
            config.setDeduplicateReferences(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1138

    
1139
            config.setGetSiblings(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1140
            config.setIgnoreAuthorship(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1141
            config.setIgnoreImportOfExistingSpecimen(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1142
            config.setMapUnitIdToAccessionNumber(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1143
            config.setMapUnitIdToBarcode(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1144
            config.setMapUnitIdToCatalogNumber(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1145
            config.setMoveNewTaxaToDefaultClassification(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1146
            config.setOverwriteExistingSpecimens(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1147
            config.setReuseExistingDescriptiveGroups(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1148
            config.setReuseExistingMetaData(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1149
            config.setReuseExistingTaxaWhenPossible(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1150
            config.setNomenclaturalCode(NomenclaturalCode.getByKey(PreferencesUtil.getPreferenceStore().getString(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1151
            return config;
1152

    
1153
        }
1154
            ICdmRepository controller;
1155
            controller = CdmStore.getCurrentApplicationConfiguration();
1156
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AbcdImportConfig);
1157
            CdmPreference preference = null;
1158
            if (controller == null){
1159
                return null;
1160
            }
1161
            preference = controller.getPreferenceService().find(key);
1162
            if (preference == null){
1163
                return config;
1164
             } else{
1165
             String configString = preference.getValue();
1166
             String[] configArray = configString.split(";");
1167

    
1168
             for (String configItem: configArray){
1169
                 String[] keyValue = configItem.split(":");
1170
                 String keyString = keyValue[0];
1171
                 String valueString = keyValue[1];
1172
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1173
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1174
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1175
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1176
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1177
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1178
                 }else if (keyString.equals("ignoreAuthorship")){
1179
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1180
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1181
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1182
                 }else if (keyString.equals("reuseExistingMetaData")){
1183
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1184
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1185
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1186
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1187
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1188
                 }else if (keyString.equals("deduplicateReferences")){
1189
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1190
                 }else if (keyString.equals("deduplicateClassifications")){
1191
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1192
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1193
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1194
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1195
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1196
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1197
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1198
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1199
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1200
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1201
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1202
                 }else if (keyString.equals("nomenclaturalCode")){
1203
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1204
                 }else{
1205
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1206
                 }
1207

    
1208
            }
1209
        }
1210
        return config;
1211

    
1212

    
1213

    
1214
    }
1215

    
1216
    /**
1217
    *
1218
    */
1219
   public NameDetailsConfigurator createLocalNameDetailsViewConfig(boolean local) {
1220
       NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1221
       if (local){
1222
          config.setSimpleDetailsViewActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION));
1223
          config.setAppendedPhraseActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1224
          config.setAtomisedEpithetsActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1225
          config.setAuthorshipSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1226
          config.setLSIDActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID));
1227
          config.setNameApprobiationActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_APPROBATION));
1228
          config.setNameCacheActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_CACHE));
1229
          config.setNameRelationsSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1230
          config.setNomenclaturalCodeActived(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1231
          config.setNomenclaturalStatusSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1232
          config.setNomenclaturalReferenceSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1233
          config.setProtologueActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1234
          config.setRankActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK));
1235
          config.setTaxonSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON));
1236
          config.setTypeDesignationSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1237
          config.setHybridActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID));
1238
       }else{
1239

    
1240
       }
1241

    
1242
      return config;
1243
   }
1244

    
1245

    
1246
   public static void saveConfigToPrefernceStore(NameDetailsConfigurator config) {
1247
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION,
1248
               config.isSimpleDetailsViewActivated());
1249
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1250
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1251
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1252
               config.isNomenclaturalCodeActived());
1253
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAMECACHE,
1254
               config.isNameCacheActivated());
1255
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1256
               config.isAppendedPhraseActivated());
1257
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1258
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1259
               config.isAtomisedEpithetsActivated());
1260
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE,
1261
               config.isAuthorCacheActivated());
1262
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1263
               config.isAuthorshipSectionActivated());
1264
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1265
               config.isNomenclaturalReferenceSectionActivated());
1266
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1267
               config.isNomenclaturalStatusSectionActivated());
1268
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1269
               config.isProtologueActivated());
1270
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1271
               config.isTypeDesignationSectionActivated());
1272
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1273
               config.isNameRelationsSectionActivated());
1274
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID,
1275
               config.isHybridActivated());
1276

    
1277
   }
1278

    
1279
/**
1280
 * @return
1281
 */
1282
public static boolean isSortTaxaByRankAndName() {
1283

    
1284
    return getPreferenceStore().getBoolean(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1285
}
1286

    
1287
/**
1288
 * @return
1289
 */
1290
public static boolean isSortNamedAreaByOrderInVocabulary() {
1291

    
1292
    return getPreferenceStore().getBoolean(IPreferenceKeys.SORT_NAMED_AREA_BY_VOCABULARY_ORDER);
1293
}
1294

    
1295
public static void setSortNamedAreasByOrderInVocabulary(boolean isSortByVocabularyOrder) {
1296
    getPreferenceStore().setValue(IPreferenceKeys.SORT_NAMED_AREA_BY_VOCABULARY_ORDER, isSortByVocabularyOrder);
1297

    
1298
}
1299

    
1300
/**
1301
 * <p>
1302
 * setPreferredNamedAreasForDistributionEditor
1303
 * </p>
1304
 *
1305
 * @param saveCheckedElements
1306
 * @param saveGrayedElements
1307
 */
1308
public static void setLastSelectedReference(
1309
        List<String> lastSelectedReferences) {
1310

    
1311
        IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1312
        preferenceStore.setValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1313
    }
1314

    
1315
/**
1316
 * <p>
1317
 * setPreferredNamedAreasForDistributionEditor
1318
 * </p>
1319
 *
1320
 * @param saveCheckedElements
1321
 * @param saveGrayedElements
1322
 */
1323
public static List<String> getLastSelectedReferences() {
1324

    
1325
        IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1326
        String lastSelected = preferenceStore.getString(PreferencesUtil.LAST_SELECTED_REFERENCES);
1327
        List<String> result = new ArrayList<>();
1328
        Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1329
        return result;
1330
    }
1331

    
1332

    
1333
/**
1334
 * <p>
1335
 * setPreferredNamedAreasForDistributionEditor
1336
 * </p>
1337
 *
1338
 * @param saveCheckedElements
1339
 * @param saveGrayedElements
1340
 */
1341
public static CdmPreference setPreferredNamedAreasForDistributionEditor(
1342
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1343
    if (local){
1344
        IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1345
        preferenceStore.setValue(PreferencesUtil.DISTRIBUTION_AREA_OCCURENCE_STATUS, saveCheckedElements);
1346
        preferenceStore.setValue(PreferencesUtil.DISTRIBUTION_AREA_OCCURENCE_STATUS_GRAYED, saveGrayedElements);
1347

    
1348
    }
1349
    else{
1350
        ICdmRepository controller;
1351

    
1352
//        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AvailableDistributionAreaTerms);
1353
        CdmPreference preference = null;
1354

    
1355
        if (saveCheckedElements == null){
1356
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1357
//            preference = controller.getPreferenceService().find(key);
1358
            if (preference == null){
1359
                return null;
1360
            } else{
1361
                String[] uuids = StringUtils.splitByWholeSeparator(saveCheckedElements, ",");
1362
                List<UUID> uuidList = new ArrayList();
1363
                for (String uuidString: uuids){
1364
                    uuidList.add(UUID.fromString(uuidString.trim()));
1365
                }
1366
                getPreferenceStore().setValue(DISTRIBUTION_AREA_OCCURENCE_STATUS,
1367
                        saveCheckedElements);
1368

    
1369
                return preference;
1370
            }
1371
        } else{
1372
            controller = CdmStore.getCurrentApplicationConfiguration();
1373
            preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1374
            controller.getPreferenceService().set(preference);
1375
            getPreferenceStore().setValue(DISTRIBUTION_AREA_OCCURENCE_STATUS,
1376
                    saveCheckedElements);
1377

    
1378
        }
1379
    }
1380
    return null;
1381

    
1382

    
1383

    
1384
}
1385

    
1386

    
1387

    
1388

    
1389

    
1390
}
(19-19/24)