Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

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

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

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

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

    
82
	/**
83
	 *
84
	 */
85
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
86

    
87
	public static final String P2_REPOSITORIES_DELIM = ",";
88
	public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
89

    
90
	private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
91

    
92
	/**
93
	 * <p>
94
	 * getPreferenceStore
95
	 * </p>
96
	 *
97
	 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
98
	 */
99
	public static IPreferenceStore getPreferenceStore() {
100
		return TaxeditorStorePlugin.getDefault().getPreferenceStore();
101
	}
102

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

    
140
    				getPreferenceStore().setValue(CDM_NOMENCLATURAL_CODE_KEY,
141
    				        preferenceKey);
142
    				getPreferenceStore().setValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY,preference.isAllowOverride());
143
    				return preference;
144
    			}
145
    		} else{
146
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceKey);
147
    			controller.getPreferenceService().set(preference);
148

    
149
    		}
150
	    }
151
        return null;
152

    
153

    
154

    
155
	}
156

    
157
	public static NomenclaturalCode getPreferredNomenclaturalCode(){
158
	    if (getPreferenceStore().getBoolean(OVERRIDE_NOMENCLATURAL_CODE_KEY)) {
159
            return getPreferredNomenclaturalCode(true);
160
        } else{
161
            return getPreferredNomenclaturalCode(false);
162
        }
163
	}
164

    
165
	/**
166
	 * <p>
167
	 * getPreferredNomenclaturalCode
168
	 * </p>
169
	 *
170
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
171
	 */
172
	public static NomenclaturalCode getPreferredNomenclaturalCode(boolean useLocal) {
173

    
174
		CdmPreference pref = null;
175
		if (!useLocal){
176
		    pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
177
		}
178

    
179
	    String preferredCode;
180
	    if(pref == null){
181
	    	preferredCode = getPreferenceStore().getString(
182
					PREFERRED_NOMENCLATURAL_CODE_KEY);
183

    
184
	    }else{
185
	    	preferredCode = pref.getValue();
186
	    }
187

    
188
		for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
189
			if (getPreferenceKey(code).equals(preferredCode)) {
190
				return code;
191
			}
192
		}
193
		return null;
194
	}
195

    
196
	public static boolean isShowTaxonAssociations(){
197
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
198
            return getPreferenceStore().getBoolean(SHOW_TAXON_ASSOCIATIONS);
199
        } else{
200
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowTaxonAssociations);
201

    
202
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
203
        }
204
    }
205

    
206
	public static boolean isShowLifeForm(){
207
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
208
            return getPreferenceStore().getBoolean(SHOW_LIFE_FORM);
209
        } else{
210
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowLifeForm);
211

    
212
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
213
        }
214
    }
215

    
216
	public static boolean isDeterminationOnlyForFieldUnits(){
217
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
218
            return getPreferenceStore().getBoolean(DETERMINATION_ONLY_FOR_FIELD_UNITS);
219
        } else{
220
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.DeterminationOnlyForFieldUnits);
221

    
222
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
223
        }
224
    }
225

    
226
	public static boolean isCollectingAreaInGeneralSection(){
227
        if (getPreferenceStore().getBoolean(OVERRIDE_SPECIMEN_PREF) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_SPECIMEN_PREF)) {
228
            return getPreferenceStore().getBoolean(SHOW_COLLECTING_AREAS_IN_GENERAL_SECTION);
229
        } else{
230
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.ShowCollectingAreasInGeneralSection);
231

    
232
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
233
        }
234
    }
235

    
236
	public static boolean isShowSimpleDetailsView(){
237
        if (getPreferenceStore().getBoolean(OVERRIDE_NAME_DETAILS) && getPreferenceStore().getBoolean(ALLOW_OVERRIDE_NAME_DETAILS)) {
238
            return getPreferenceStore().getBoolean(SHOW_SIMPLE_NAME_DETAILS_SECTION);
239
        } else{
240
            CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
241

    
242
            return pref!=null?Boolean.valueOf(pref.getValue()):false;
243
        }
244
    }
245

    
246

    
247

    
248
    public static CdmPreference getPreferenceFromDB(PreferencePredicate predicate){
249
        ICdmRepository controller;
250
        CdmPreference pref = null;
251

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

    
262
        return pref;
263

    
264
    }
265

    
266

    
267
	public static String getPreferredDefaultLangugae(){
268
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
269
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
270
	        return preferredLanguage;
271
	    }
272
	    return null;
273
	}
274

    
275
	public static boolean isShowMediaPreview(){
276
        boolean isShowMediaPreview = getPreferenceStore().getBoolean(SHOW_MEDIA_PREVIEW);
277
        return isShowMediaPreview;
278
    }
279

    
280
	/**
281
	 * Get the match strategy for the given class that was stored in preferences
282
	 * or the default strategy if it was not stored in preferences
283
	 *
284
	 * @param clazz
285
	 *            a {@link java.lang.Class} object.
286
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
287
	 */
288
	public static IMatchStrategy getMatchStrategy(Class clazz) {
289
		String className = clazz.getName();
290
		if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
291
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
292

    
293
			for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
294
				String matchModeName = getPreferenceStore().getString(
295
						getMatchStrategyFieldName(className, fieldName));
296
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
297
				try {
298
					matchStrategy.setMatchMode(fieldName, matchMode);
299
				} catch (MatchException e) {
300
					MessagingUtils.error(PreferencesUtil.class, e);
301
					throw new RuntimeException(e);
302
				}
303
			}
304

    
305
			return matchStrategy;
306
		}
307
		return getDefaultMatchStrategy(clazz);
308
	}
309

    
310
	/**
311
	 * Stores a matchStrategy into the preference store.
312
	 *
313
	 * @param matchStrategy
314
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
315
	 *            object.
316
	 */
317
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
318
		String className = matchStrategy.getMatchClass().getName();
319
		getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
320

    
321
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
322

    
323
		for (String fieldName : matchFields) {
324
			getPreferenceStore().setValue(
325
					getMatchStrategyFieldName(className, fieldName),
326
					matchStrategy.getMatchMode(fieldName).name());
327
		}
328
	}
329

    
330
	/**
331
	 * Helper method to create the preference property for a match field.
332
	 *
333
	 * @param className
334
	 * @param fieldName
335
	 * @return
336
	 */
337
	private static String getMatchStrategyFieldName(String className,
338
			String fieldName) {
339
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
340
	}
341

    
342
	/**
343
	 * Returns the default match strategy for a given class.
344
	 *
345
	 * @param clazz
346
	 *            a {@link java.lang.Class} object.
347
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
348
	 */
349
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
350
		return DefaultMatchStrategy.NewInstance(clazz);
351
	}
352

    
353
	/**
354
	 * <p>
355
	 * getDateFormatPattern
356
	 * </p>
357
	 *
358
	 * @return a {@link java.lang.String} object.
359
	 */
360
	public static String getDateFormatPattern() {
361
		// TODO make this configurable in properties
362
		String pattern = "Y-M-d H:m";
363
		return pattern;
364
	}
365

    
366
	/**
367
	 * <p>
368
	 * addTermToPreferredTerms
369
	 * </p>
370
	 *
371
	 * @param term
372
	 *            a T object.
373
	 * @param <T>
374
	 *            a T object.
375
	 */
376
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
377

    
378
		// VocabularyEnum vocabulary =
379
		// VocabularyEnum.getVocabularyEnum(term.getClass());
380
		//
381
		// getPreferenceStore().setValue(getPreferenceKey(term),
382
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
383
		//
384
		// firePreferencesChanged(term.getClass());
385
	}
386

    
387
	/**
388
	 * Construct a unique key using the CdmBase object's uuid
389
	 *
390
	 * @param cdmBase
391
	 * @return
392
	 */
393
	private static String getPreferenceKey(ICdmBase cdmBase) {
394
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
395

    
396
		String key = cdmBase.getClass().getName().concat(".")
397
				.concat(cdmBase.getUuid().toString());
398
		if (key.contains("javassist")) {
399
			MessagingUtils.info("proxy");
400
		}
401
		return key;
402
	}
403

    
404
	/**
405
	 * Construct a unique key using the CdmBase object's uuid
406
	 *
407
	 * @param cdmBase
408
	 * @return
409
	 */
410
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
411
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
412
		String key = simpleTerm.getClass().getName().concat(".")
413
				.concat(simpleTerm.getUuid().toString());
414
		if (key.contains("javassist")) {
415
			MessagingUtils.warn(PreferencesUtil.class,
416
					"Trying to persist a preference based on a proxy class.");
417
		}
418
		return key;
419
	}
420

    
421

    
422

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

    
440
	/**
441
	 * Retrieves search preferences from the preference store
442
	 *
443
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
444
	 */
445
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
446
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
447

    
448
		configurator.setDoTaxa(getPreferenceStore().getBoolean(
449
				TAXON_SERVICE_CONFIGURATOR_TAXA));
450
		configurator.setDoSynonyms(getPreferenceStore().getBoolean(
451
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
452
		configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
453
				TAXON_SERVICE_CONFIGURATOR_NAMES));
454
		configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
455
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
456
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getPreferenceStore().getString(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
457

    
458
		return configurator;
459
	}
460

    
461
	/**
462
	 * create new preferences, setting all search options to true
463
	 *
464
	 * @return a
465
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
466
	 *         object.
467
	 */
468
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
469
		IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
470

    
471
		configurator.setDoTaxa(true);
472
		configurator.setDoSynonyms(true);
473
		configurator.setDoNamesWithoutTaxa(true);
474
		configurator.setDoTaxaByCommonNames(true);
475

    
476
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
477
				"name", "name.$", "relationsFromThisTaxon.$"));
478

    
479
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
480
				"name", "name.$", "synonyms.relatedTo.*"));
481

    
482
		// DEFAULT VALUES
483
		// match mode is a simple like, actually all other match modes are kind
484
		// of bogus
485
		configurator
486
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
487
		// we set page number and size here as this should always be unlimited
488
		configurator.setPageNumber(0);
489
		// TODO currently limit results to 10000
490
		configurator.setPageSize(10000);
491

    
492
		return configurator;
493
	}
494

    
495
	/**
496
	 * Store search preferences
497
	 *
498
	 * @param configurator
499
	 *            a
500
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
501
	 *            object.
502
	 */
503
	public static void setSearchConfigurator(
504
			IFindTaxaAndNamesConfigurator configurator) {
505
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
506
				configurator.isDoTaxa());
507
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
508
				configurator.isDoSynonyms());
509
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
510
				configurator.isDoNamesWithoutTaxa());
511
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
512
				configurator.isDoTaxaByCommonNames());
513
	}
514

    
515
	/**
516
	 * <p>
517
	 * firePreferencesChanged
518
	 * </p>
519
	 *
520
	 * @param clazz
521
	 *            a {@link java.lang.Class} object.
522
	 */
523
	public static void firePreferencesChanged(Class clazz) {
524
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
525
				null, clazz);
526
	}
527

    
528
	/**
529
	 * Set default values for preferences
530
	 */
531
	public static void setDefaults() {
532
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
533
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
534
				true);
535
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
536
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
537
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
538
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
539
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
540
				"http://www.biodiversitylibrary.org/openurl");
541
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
542
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
543
		getPreferenceStore().setDefault(IPreferenceKeys.DISTRIBUTION_AREA_PREFRENCES_ACTIVE, false);
544
		getPreferenceStore().setDefault(CHECKLIST_ID_IN_VOCABULARY, true);
545
		getPreferenceStore().setDefault(CHECKLIST_SYMBOL, false);
546
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, true);
547
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE, true);
548
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, true);
549
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_HYBRID, true);
550
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_LSID, true);
551
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, true);
552
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAMECACHE, true);
553
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, true);
554
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, true);
555
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, true);
556
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, true);
557
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_RANK, true);
558
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, true);
559
		getPreferenceStore().setDefault(SORT_NODES_NATURALLY, false);
560
		getPreferenceStore().setDefault(SORT_NODES_ALPHABETICALLY, false);
561
		getPreferenceStore().setDefault(SORT_TAXA_BY_RANK_AND_NAME, true);
562

    
563
	}
564

    
565
	/**
566
	 * <p>
567
	 * checkNomenclaturalCode
568
	 * </p>
569
	 */
570
	public static void checkNomenclaturalCode() {
571
		// First time Editor is opened, no nomenclatural code has been set
572

    
573

    
574
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
575
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
576
		}
577

    
578

    
579

    
580
	}
581
	public static void setNomenclaturalCodePreferences(){
582
	    ICdmRepository controller;
583
        controller = CdmStore.getCurrentApplicationConfiguration();
584
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
585
        CdmPreference preference = null;
586
        if (controller == null){
587
            return ;
588
        }
589
        preference = controller.getPreferenceService().find(key);
590
        if (preference == null){
591
            return;
592
        }
593
        getPreferenceStore().setValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
594

    
595
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
596
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
597
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
598

    
599
        getPreferenceStore().setValue(CDM_NOMENCLATURAL_CODE_KEY,
600
                getPreferenceKey(preferredCode));
601

    
602
        if (!preference.isAllowOverride()){
603
            getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
604
                    getPreferenceKey(preferredCode));
605
        }
606
	}
607

    
608
	public static void checkDefaultLanguage(){
609
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
610
	       Shell shell = AbstractUtility.getShell();
611
	       int open = new DefaultLanguageDialog(shell).open();
612
	       if(open == Window.OK){
613
	           PlatformUI.getWorkbench().restart();
614
	       }
615
	    }else{
616
	        //TODO:In case of a reinstall, the config.ini will be overwritten
617
	        //     here you create config.ini with the stored key from preferences
618
	    }
619
	}
620

    
621
	/**
622
	 * <p>
623
	 * getMapServiceAccessPoint
624
	 * </p>
625
	 *
626
	 * @return a {@link java.lang.String} object.
627
	 */
628
	public static String getMapServiceAccessPoint() {
629
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
630
	}
631

    
632
	/**
633
	 * <p>
634
	 * shouldConnectAtStartUp
635
	 * </p>
636
	 *
637
	 * @return a boolean.
638
	 */
639
	public static boolean shouldConnectAtStartUp() {
640
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
641
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
642
		return false;
643
	}
644

    
645
	/**
646
	 * <p>
647
	 * getDefaultFeatureTreeForTextualDescription
648
	 * </p>
649
	 *
650
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
651
	 */
652
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
653
		String uuidString = getPreferenceStore().getString(
654
				FEATURE_TREE_DEFAULT_TEXT);
655
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
656
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
657
	}
658

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

    
673
	/**
674
	 * <p>
675
	 * setSortRanksHierarchichally
676
	 * </p>
677
	 *
678
	 * @param selection
679
	 *            a boolean.
680
	 */
681
	public static void setSortRanksHierarchichally(boolean selection) {
682
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
683
	}
684

    
685
	/**
686
	 * <p>
687
	 * getSortRanksHierarchichally
688
	 * </p>
689
	 *
690
	 * @return a boolean.
691
	 */
692
	public static boolean getSortRanksHierarchichally() {
693
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
694
	}
695

    
696
	public static boolean isMultilanguageTextEditingCapability() {
697
		return getPreferenceStore().getBoolean(
698
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
699
	}
700

    
701
	public static Language getGlobalLanguage() {
702

    
703

    
704
		String languageUuidString = getPreferenceStore().getString(
705
				GLOBAL_LANGUAGE_UUID);
706

    
707
		if(!CdmStore.isActive()) {
708
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
709
            return null;
710
        }
711

    
712
		if (CdmUtils.isBlank(languageUuidString)) {
713
			return Language.getDefaultLanguage();
714
		}
715

    
716
		UUID languageUuid = UUID.fromString(languageUuidString);
717
		return (Language) CdmStore.getService(ITermService.class).load(
718
				languageUuid);
719
	}
720

    
721
	public static void setGlobalLanguage(Language language) {
722
	    if(language != null) {
723
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
724
	        CdmStore.setDefaultLanguage(language);
725
	    }
726

    
727
	}
728

    
729
	/**
730
	 * @return
731
	 */
732
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
733
		List<MarkerType> markerTypes = CdmStore.getTermManager()
734
				.getPreferredTerms(MarkerType.class);
735

    
736
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
737

    
738
		for (MarkerType markerType : markerTypes) {
739
			String name = getMarkerTypeEditingPreferenceKey(markerType);
740
			Boolean value = getPreferenceStore().getBoolean(name);
741

    
742
			result.put(markerType, value);
743
		}
744

    
745
		return result;
746
	}
747

    
748
	/**
749
	 * @param markerTypeEditingMap
750
	 */
751
	public static void setEditMarkerTypePreferences(
752
			Map<MarkerType, Boolean> markerTypeEditingMap) {
753
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
754
			String name = getMarkerTypeEditingPreferenceKey(markerType);
755
			getPreferenceStore().setValue(name,
756
					markerTypeEditingMap.get(markerType));
757
		}
758

    
759
	}
760

    
761
	private static String getMarkerTypeEditingPreferenceKey(
762
			MarkerType markerType) {
763
		markerType = HibernateProxyHelper.deproxy(markerType);
764
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
765
	}
766

    
767
	/**
768
	 * <p>
769
	 * setEditMarkerTypePreference
770
	 * </p>
771
	 *
772
	 * @param input
773
	 *            a {@link org.eclipse.ui.IEditorInput} object.
774
	 * @param markerType
775
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
776
	 * @param edit
777
	 *            a boolean.
778
	 */
779
	public static void setEditMarkerTypePreference(MarkerType markerType,
780
			boolean edit) {
781
		getPreferenceStore().setValue(
782
				getMarkerTypeEditingPreferenceKey(markerType), edit);
783
	}
784

    
785
	/**
786
	 * @return
787
	 */
788
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
789
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
790
				.NewInstance();
791
		configurator.setMoveDerivedUnitMediaToGallery(true);
792
		configurator.setMoveFieldObjectMediaToGallery(true);
793
		return configurator;
794
	}
795

    
796
	/**
797
	 * This method will write language properties to the config.ini located in the configuration folder
798
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
799
	 *
800
	 * @param setLanguage 0 is for german and 1 for english.
801
	 * @throws IOException
802
	 */
803
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
804
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
805
        //give warning to user if the directory has no write access
806
        if(file == null){
807
            throw new IOException();
808
        }
809
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
810
        switch(setLanguage){
811
        case 0:
812
            properties.setProperty("osgi.nl", "de");
813
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
814
            break;
815
        case 1:
816
            properties.setProperty("osgi.nl", "en");
817
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
818
            break;
819
        default:
820
            break;
821
        }
822
        save(file+"/config.ini", properties);
823
    }
824

    
825
    /**
826
     * This method loads a property from a given file and returns it.
827
     *
828
     * @param filename
829
     * @return
830
     * @throws IOException
831
     */
832
    private Properties load(String filename) throws IOException {
833
        FileInputStream in = new FileInputStream(filename);
834
        Properties prop = new Properties();
835
        prop.load(in);
836
        in.close();
837
        return prop;
838
    }
839

    
840
    /**
841
     * This method saves a property to the specified file.
842
     *
843
     * @param filename
844
     * @param properties
845
     * @throws IOException
846
     */
847
    private void save(String filename, Properties properties) throws IOException{
848
        FileOutputStream fos =  new FileOutputStream(filename);
849
        properties.store(fos, "");
850
        fos.close();
851
    }
852

    
853
    /**
854
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
855
     *
856
     * @param p2Repos
857
     */
858
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
859
        StringBuilder sb = new StringBuilder();
860
        for(MetadataRepositoryElement p2Repo : p2Repos) {
861
            sb.append(P2_REPOSITORIES_DELIM);
862
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
863
                sb.append("-");
864
            } else {
865
                sb.append(p2Repo.getName());
866
            }
867
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
868
            sb.append(p2Repo.getLocation().toString());
869
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
870
            sb.append(String.valueOf(p2Repo.isEnabled()));
871
        }
872
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
873
    }
874

    
875

    
876
    /**
877
     * Retrieves a list of previously saved P2 repositories
878
     *
879
     * @return
880
     */
881
    public static List<MetadataRepositoryElement> getP2Repositories() {
882
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
883
        String p2ReposPref =  getPreferenceStore().getString(P2_REPOSITORY_LIST);
884
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
885
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
886

    
887
            while(p2ReposPrefST.hasMoreTokens()) {
888
                String p2RepoStr = p2ReposPrefST.nextToken();
889
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
890
                if(p2ReposStrST.countTokens()==3) {
891
                    String nickname = p2ReposStrST.nextToken();
892
                    URI uri = null;
893
                    try {
894
                        uri = new URI(p2ReposStrST.nextToken());
895
                    } catch (URISyntaxException e) {
896
                        continue;
897
                    }
898
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
899
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
900
                    mre.setNickname(nickname);
901
                    mre.setEnabled(enabled);
902
                    p2Repos.add(mre);
903
                }
904
            }
905
        }
906

    
907
        return p2Repos;
908
    }
909

    
910
    /**
911
     * enables/disables nested composite. <br>
912
     *
913
     * @param ctrl - Composite to be en-/disabeld
914
     * @param enabled - boolean
915
     */
916
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
917
        if (ctrl instanceof Composite) {
918
            Composite comp = (Composite) ctrl;
919
            for (Control c : comp.getChildren()) {
920
                recursiveSetEnabled(c, enabled);
921
            }
922
        } else {
923
            ctrl.setEnabled(enabled);
924
        }
925
    }
926

    
927
    /**
928
	 * <p>
929
	 * getSortRanksNaturally
930
	 * </p>
931
    	 *
932
    	 * @return a boolean.
933
	 */
934
	public static boolean getSortNodesNaturally() {
935
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
936
	}
937

    
938
	/**
939
	 * <p>
940
	 * setSortRanksNaturally
941
	 * </p>
942
	 *
943
	 * @param selection
944
	 *            a boolean.
945
	 */
946
	public static void setSortNodesNaturally(boolean selection) {
947
		getPreferenceStore().setValue(SORT_NODES_NATURALLY, selection);
948
	}
949

    
950

    
951
	/**
952
	 * <p>
953
	 * getSortRanksNaturally
954
	 * </p>
955
	 *
956
	 * @return a boolean.
957
	 */
958
	public static boolean getSortNodesStrictlyAlphabetically() {
959
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
960
	}
961

    
962
	/**
963
	 * <p>
964
	 * setSortRanksNaturally
965
	 * </p>
966
	 *
967
	 * @param selection
968
	 *            a boolean.
969
	 */
970
	public static void setSortNodesStrictlyAlphabetically(boolean selection) {
971
		getPreferenceStore().setValue(SORT_NODES_ALPHABETICALLY, selection);
972
	}
973

    
974
	/**
975
	 * <p>
976
	 * setStoreNavigatorState
977
	 * </p>
978
	 *
979
	 * @param selection
980
	 *            a boolean.
981
	 */
982
	public static boolean isStoreNavigatorState() {
983
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
984

    
985
	}
986

    
987
	/**
988
	 * <p>
989
	 * setStoreNavigatorState
990
	 * </p>
991
	 *
992
	 * @param selection
993
	 *            a boolean.
994
	 */
995
	public static void setStoreNavigatorState(boolean selection) {
996
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
997

    
998
	}
999

    
1000
    /**
1001
     * @return
1002
     */
1003
    public static boolean isShowUpWidgetIsDisposedMessages() {
1004
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1005
    }
1006
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1007
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1008
    }
1009

    
1010
    /**
1011
     * @return
1012
     */
1013
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1014
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
1015
    }
1016
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
1017
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
1018
    }
1019

    
1020
    /**
1021
     * @return
1022
     */
1023
    public static boolean isShowSymbolInChecklistEditor() {
1024
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SYMBOL);
1025
    }
1026
    public static void setShowSymbolInChecklistEditor(boolean selection) {
1027
        getPreferenceStore().setValue(CHECKLIST_SYMBOL, selection);
1028
    }
1029

    
1030
    /**
1031
     * @return
1032
     */
1033
    public static boolean isShowRankInChecklistEditor() {
1034
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
1035
    }
1036
    public static void setShowRankInChecklistEditor(boolean selection) {
1037
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
1038
    }
1039

    
1040
    /**
1041
     * @param object
1042
     * @param b
1043
     * @return
1044
     */
1045
    public static NameDetailsConfigurator setPreferredNameDetailsConfiguration( boolean local) {
1046
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1047

    
1048
        CdmPreference preference = null;
1049

    
1050
        if (!local) {
1051
            preference = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1052
        }
1053
        if (preference == null){
1054
            return null;
1055
        }
1056

    
1057
        getPreferenceStore().setValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1058

    
1059
        //the preference value is build like this:
1060
        //<section1>:true;<section2>:false....
1061

    
1062
        String value = preference.getValue();
1063
        String [] sections = value.split(";");
1064
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1065
        String[] sectionValues;
1066
        for (String sectionValue: sections){
1067
            sectionValues = sectionValue.split(":");
1068
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1069
        }
1070

    
1071
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1072

    
1073
//        getPreferenceStore().setValue(SHOW_SIMPLE_NAME_DETAILS_TAXON,
1074
//                (getValue(sectionMap, "taxon")));
1075
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1076

    
1077
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_LSID,
1078
//                (getValue(sectionMap, "lsid")));
1079
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1080

    
1081
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1082
//                (getValue(sectionMap, "nc")));
1083
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1084

    
1085
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1086
//                (getValue(sectionMap, "ap")));
1087
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1088

    
1089
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_RANK,
1090
//                (getValue(sectionMap, "rank")));
1091
        config.setRankActivated(getValue(sectionMap, "rank"));
1092

    
1093

    
1094
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1095
//                (getValue(sectionMap, "atomisedEpithets")));
1096
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1097

    
1098
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1099
//                (getValue(sectionMap,"author")));
1100
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1101

    
1102
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1103
//                (getValue(sectionMap, "nomRef")));
1104
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1105

    
1106
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1107
//                (getValue(sectionMap, "nomStat")));
1108
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1109

    
1110

    
1111
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1112
//                (getValue(sectionMap,"protologue")));
1113
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1114

    
1115
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1116
//                (getValue(sectionMap,"typeDes")));
1117
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1118

    
1119
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1120
//                (getValue(sectionMap,"nameRelation")));
1121
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1122

    
1123
//        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_HYBRID,
1124
//                (getValue(sectionMap, "hybrid")));
1125
        config.setHybridActivated(getValue(sectionMap,"hybrid"));
1126

    
1127
        return config;
1128
    }
1129

    
1130
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1131
		if (sectionMap.containsKey(string)){
1132
			return sectionMap.get(string);
1133
		}else{
1134
			return true;
1135
		}
1136

    
1137
	}
1138

    
1139

    
1140

    
1141
    /**
1142
     * <p>
1143
     * setAbcdConfigurator
1144
     * </p>
1145
     *
1146
     * @param preferredConfiguration
1147
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1148
     *            object.
1149
     */
1150
    public static Abcd206ImportConfigurator getAbcdImportConfigurationPreference(boolean useLocal) {
1151

    
1152
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1153

    
1154
        if (useLocal){
1155
            config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1156

    
1157
            config.setAddMediaAsMediaSpecimen(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1158

    
1159
            config.setAllowReuseOtherClassifications(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1160
            config.setDeduplicateClassifications(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1161
            config.setDeduplicateReferences(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1162

    
1163
            config.setGetSiblings(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1164
            config.setIgnoreAuthorship(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1165
            config.setIgnoreImportOfExistingSpecimen(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1166
            config.setMapUnitIdToAccessionNumber(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1167
            config.setMapUnitIdToBarcode(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1168
            config.setMapUnitIdToCatalogNumber(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1169
            config.setMoveNewTaxaToDefaultClassification(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1170
            config.setOverwriteExistingSpecimens(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1171
            config.setReuseExistingDescriptiveGroups(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1172
            config.setReuseExistingMetaData(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1173
            config.setReuseExistingTaxaWhenPossible(PreferencesUtil.getPreferenceStore().getBoolean(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1174
            config.setNomenclaturalCode(NomenclaturalCode.getByKey(PreferencesUtil.getPreferenceStore().getString(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1175
            return config;
1176

    
1177
        }
1178
            ICdmRepository controller;
1179
            controller = CdmStore.getCurrentApplicationConfiguration();
1180
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AbcdImportConfig);
1181
            CdmPreference preference = null;
1182
            if (controller == null){
1183
                return null;
1184
            }
1185
            preference = controller.getPreferenceService().find(key);
1186
            if (preference == null){
1187
                return config;
1188
             } else{
1189
             String configString = preference.getValue();
1190
             String[] configArray = configString.split(";");
1191

    
1192
             for (String configItem: configArray){
1193
                 String[] keyValue = configItem.split(":");
1194
                 String keyString = keyValue[0];
1195
                 String valueString = keyValue[1];
1196
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1197
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1198
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1199
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1200
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1201
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1202
                 }else if (keyString.equals("ignoreAuthorship")){
1203
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1204
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1205
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1206
                 }else if (keyString.equals("reuseExistingMetaData")){
1207
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1208
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1209
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1210
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1211
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1212
                 }else if (keyString.equals("deduplicateReferences")){
1213
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1214
                 }else if (keyString.equals("deduplicateClassifications")){
1215
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1216
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1217
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1218
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1219
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1220
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1221
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1222
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1223
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1224
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1225
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1226
                 }else if (keyString.equals(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)){
1227
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1228
                 }else{
1229
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1230
                 }
1231

    
1232
            }
1233
        }
1234
        return config;
1235

    
1236

    
1237

    
1238
    }
1239

    
1240
    /**
1241
    *
1242
    */
1243
   public NameDetailsConfigurator createLocalNameDetailsViewConfig(boolean local) {
1244
       NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1245
       if (local){
1246
          config.setSimpleDetailsViewActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION));
1247
          config.setAppendedPhraseActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1248
          config.setAtomisedEpithetsActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1249
          config.setAuthorshipSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1250
          config.setLSIDActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID));
1251
          config.setNameApprobiationActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_APPROBATION));
1252
          config.setNameCacheActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_CACHE));
1253
          config.setNameRelationsSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1254
          config.setNomenclaturalCodeActived(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1255
          config.setNomenclaturalStatusSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1256
          config.setNomenclaturalReferenceSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1257
          config.setProtologueActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1258
          config.setRankActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK));
1259
          config.setTaxonSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON));
1260
          config.setTypeDesignationSectionActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1261
          config.setHybridActivated(getPreferenceStore().getBoolean(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID));
1262
       }else{
1263

    
1264
       }
1265

    
1266
      return config;
1267
   }
1268

    
1269

    
1270
   public static void saveConfigToPrefernceStore(NameDetailsConfigurator config) {
1271
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION,
1272
               config.isSimpleDetailsViewActivated());
1273
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1274
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1275
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1276
               config.isNomenclaturalCodeActived());
1277
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAMECACHE,
1278
               config.isNameCacheActivated());
1279
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1280
               config.isAppendedPhraseActivated());
1281
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1282
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1283
               config.isAtomisedEpithetsActivated());
1284
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE,
1285
               config.isAuthorCacheActivated());
1286
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1287
               config.isAuthorshipSectionActivated());
1288
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1289
               config.isNomenclaturalReferenceSectionActivated());
1290
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1291
               config.isNomenclaturalStatusSectionActivated());
1292
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1293
               config.isProtologueActivated());
1294
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1295
               config.isTypeDesignationSectionActivated());
1296
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1297
               config.isNameRelationsSectionActivated());
1298
       PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID,
1299
               config.isHybridActivated());
1300

    
1301
   }
1302

    
1303
/**
1304
 * @return
1305
 */
1306
public static boolean isSortTaxaByRankAndName() {
1307

    
1308
    return getPreferenceStore().getBoolean(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1309
}
1310

    
1311
/**
1312
 * @return
1313
 */
1314
public static boolean isSortNamedAreaByOrderInVocabulary() {
1315

    
1316
    return getPreferenceStore().getBoolean(IPreferenceKeys.SORT_NAMED_AREA_BY_VOCABULARY_ORDER);
1317
}
1318

    
1319
public static void setSortNamedAreasByOrderInVocabulary(boolean isSortByVocabularyOrder) {
1320
    getPreferenceStore().setValue(IPreferenceKeys.SORT_NAMED_AREA_BY_VOCABULARY_ORDER, isSortByVocabularyOrder);
1321

    
1322
}
1323

    
1324
/**
1325
 * <p>
1326
 * setPreferredNomenclaturalCode
1327
 * </p>
1328
 *
1329
 * @param preferredCode
1330
 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
1331
 *            object.
1332
 */
1333
public static CdmPreference setPreferredNamedAreasForDistributionEditor(
1334
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1335
    if (local){
1336
        IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1337
        preferenceStore.setValue(PreferencesUtil.DISTRIBUTION_AREA_OCCURENCE_STATUS, saveCheckedElements);
1338
        preferenceStore.setValue(PreferencesUtil.DISTRIBUTION_AREA_OCCURENCE_STATUS_GRAYED, saveGrayedElements);
1339

    
1340
    }
1341
    else{
1342
        ICdmRepository controller;
1343

    
1344
//        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AvailableDistributionAreaTerms);
1345
        CdmPreference preference = null;
1346

    
1347
        if (saveCheckedElements == null){
1348
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1349
//            preference = controller.getPreferenceService().find(key);
1350
            if (preference == null){
1351
                return null;
1352
            } else{
1353
                String[] uuids = StringUtils.splitByWholeSeparator(saveCheckedElements, ",");
1354
                List<UUID> uuidList = new ArrayList();
1355
                for (String uuidString: uuids){
1356
                    uuidList.add(UUID.fromString(uuidString.trim()));
1357
                }
1358
                getPreferenceStore().setValue(DISTRIBUTION_AREA_OCCURENCE_STATUS,
1359
                        saveCheckedElements);
1360

    
1361
                return preference;
1362
            }
1363
        } else{
1364
            controller = CdmStore.getCurrentApplicationConfiguration();
1365
            preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1366
            controller.getPreferenceService().set(preference);
1367
            getPreferenceStore().setValue(DISTRIBUTION_AREA_OCCURENCE_STATUS,
1368
                    saveCheckedElements);
1369

    
1370
        }
1371
    }
1372
    return null;
1373

    
1374

    
1375

    
1376
}
1377

    
1378

    
1379

    
1380

    
1381
}
(19-19/24)