Project

General

Profile

Download (34.5 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.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement;
30
import org.eclipse.jface.preference.IPreferenceStore;
31
import org.eclipse.jface.window.Window;
32
import org.eclipse.swt.widgets.Composite;
33
import org.eclipse.swt.widgets.Control;
34
import org.eclipse.swt.widgets.Shell;
35
import org.eclipse.ui.PlatformUI;
36

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

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

    
80
	/**
81
	 *
82
	 */
83
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
84

    
85
	public static final String P2_REPOSITORIES_DELIM = ",";
86
	public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
87

    
88

    
89

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

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

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

    
142
    		}
143
	    }
144
        return null;
145

    
146

    
147

    
148
	}
149

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

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

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

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

    
177
	    }else{
178
	    	preferredCode = pref.getValue();
179
	    }
180

    
181
		for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
182
			if (getPreferenceKey(code).equals(preferredCode)) {
183
				return code;
184
			}
185
		}
186
		return null;
187
	}
188

    
189

    
190
    private static CdmPreference getPreferenceFromDB(PreferencePredicate predicate){
191
        ICdmRepository controller;
192
        CdmPreference pref = null;
193

    
194
        try{
195
            controller = CdmStore.getCurrentApplicationConfiguration();
196
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), predicate);
197
            pref = controller.getPreferenceService().find(key);
198
        }catch(Exception e){
199
            e.printStackTrace();
200
        }
201

    
202
        return pref;
203

    
204
    }
205

    
206

    
207
	public static String getPreferredDefaultLangugae(){
208
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
209
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
210
	        return preferredLanguage;
211
	    }
212
	    return null;
213
	}
214

    
215
	/**
216
	 * Get the match strategy for the given class that was stored in preferences
217
	 * or the default strategy if it was not stored in preferences
218
	 *
219
	 * @param clazz
220
	 *            a {@link java.lang.Class} object.
221
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
222
	 */
223
	public static IMatchStrategy getMatchStrategy(Class clazz) {
224
		String className = clazz.getName();
225
		if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
226
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
227

    
228
			for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
229
				String matchModeName = getPreferenceStore().getString(
230
						getMatchStrategyFieldName(className, fieldName));
231
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
232
				try {
233
					matchStrategy.setMatchMode(fieldName, matchMode);
234
				} catch (MatchException e) {
235
					MessagingUtils.error(PreferencesUtil.class, e);
236
					throw new RuntimeException(e);
237
				}
238
			}
239

    
240
			return matchStrategy;
241
		}
242
		return getDefaultMatchStrategy(clazz);
243
	}
244

    
245
	/**
246
	 * Stores a matchStrategy into the preference store.
247
	 *
248
	 * @param matchStrategy
249
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
250
	 *            object.
251
	 */
252
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
253
		String className = matchStrategy.getMatchClass().getName();
254
		getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
255

    
256
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
257

    
258
		for (String fieldName : matchFields) {
259
			getPreferenceStore().setValue(
260
					getMatchStrategyFieldName(className, fieldName),
261
					matchStrategy.getMatchMode(fieldName).name());
262
		}
263
	}
264

    
265
	/**
266
	 * Helper method to create the preference property for a match field.
267
	 *
268
	 * @param className
269
	 * @param fieldName
270
	 * @return
271
	 */
272
	private static String getMatchStrategyFieldName(String className,
273
			String fieldName) {
274
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
275
	}
276

    
277
	/**
278
	 * Returns the default match strategy for a given class.
279
	 *
280
	 * @param clazz
281
	 *            a {@link java.lang.Class} object.
282
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
283
	 */
284
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
285
		return DefaultMatchStrategy.NewInstance(clazz);
286
	}
287

    
288
	/**
289
	 * <p>
290
	 * getDateFormatPattern
291
	 * </p>
292
	 *
293
	 * @return a {@link java.lang.String} object.
294
	 */
295
	public static String getDateFormatPattern() {
296
		// TODO make this configurable in properties
297
		String pattern = "Y-M-d H:m";
298
		return pattern;
299
	}
300

    
301
	/**
302
	 * <p>
303
	 * addTermToPreferredTerms
304
	 * </p>
305
	 *
306
	 * @param term
307
	 *            a T object.
308
	 * @param <T>
309
	 *            a T object.
310
	 */
311
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
312

    
313
		// VocabularyEnum vocabulary =
314
		// VocabularyEnum.getVocabularyEnum(term.getClass());
315
		//
316
		// getPreferenceStore().setValue(getPreferenceKey(term),
317
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
318
		//
319
		// firePreferencesChanged(term.getClass());
320
	}
321

    
322
	/**
323
	 * Construct a unique key using the CdmBase object's uuid
324
	 *
325
	 * @param cdmBase
326
	 * @return
327
	 */
328
	private static String getPreferenceKey(ICdmBase cdmBase) {
329
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
330

    
331
		String key = cdmBase.getClass().getName().concat(".")
332
				.concat(cdmBase.getUuid().toString());
333
		if (key.contains("javassist")) {
334
			MessagingUtils.info("proxy");
335
		}
336
		return key;
337
	}
338

    
339
	/**
340
	 * Construct a unique key using the CdmBase object's uuid
341
	 *
342
	 * @param cdmBase
343
	 * @return
344
	 */
345
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
346
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
347
		String key = simpleTerm.getClass().getName().concat(".")
348
				.concat(simpleTerm.getUuid().toString());
349
		if (key.contains("javassist")) {
350
			MessagingUtils.warn(PreferencesUtil.class,
351
					"Trying to persist a preference based on a proxy class.");
352
		}
353
		return key;
354
	}
355

    
356

    
357

    
358
	/**
359
	 * Construct a unique key using the CdmBase object's uuid
360
	 *
361
	 * @param cdmBase
362
	 * @return
363
	 */
364
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
365
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
366
		String key = definedTerm.getClass().getName().concat(".")
367
				.concat(definedTerm.getUuid().toString());
368
		if (key.contains("javassist")) {
369
			MessagingUtils.warn(PreferencesUtil.class,
370
					"Trying to persist a preference based on a proxy class.");
371
		}
372
		return key;
373
	}
374

    
375
	/**
376
	 * Retrieves search preferences from the preference store
377
	 *
378
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
379
	 */
380
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
381
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
382

    
383
		configurator.setDoTaxa(getPreferenceStore().getBoolean(
384
				TAXON_SERVICE_CONFIGURATOR_TAXA));
385
		configurator.setDoSynonyms(getPreferenceStore().getBoolean(
386
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
387
		configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
388
				TAXON_SERVICE_CONFIGURATOR_NAMES));
389
		configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
390
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
391
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getPreferenceStore().getString(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
392

    
393
		return configurator;
394
	}
395

    
396
	/**
397
	 * create new preferences, setting all search options to true
398
	 *
399
	 * @return a
400
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
401
	 *         object.
402
	 */
403
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
404
		IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
405

    
406
		configurator.setDoTaxa(true);
407
		configurator.setDoSynonyms(true);
408
		configurator.setDoNamesWithoutTaxa(true);
409
		configurator.setDoTaxaByCommonNames(true);
410

    
411
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
412
				"name", "name.$", "relationsFromThisTaxon.$"));
413

    
414
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
415
				"name", "name.$", "synonymRelations.relatedTo.*"));
416

    
417
		// DEFAULT VALUES
418
		// match mode is a simple like, actually all other match modes are kind
419
		// of bogus
420
		configurator
421
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
422
		// we set page number and size here as this should always be unlimited
423
		configurator.setPageNumber(0);
424
		// TODO currently limit results to 10000
425
		configurator.setPageSize(10000);
426

    
427
		return configurator;
428
	}
429

    
430
	/**
431
	 * Store search preferences
432
	 *
433
	 * @param configurator
434
	 *            a
435
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
436
	 *            object.
437
	 */
438
	public static void setSearchConfigurator(
439
			IFindTaxaAndNamesConfigurator configurator) {
440
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
441
				configurator.isDoTaxa());
442
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
443
				configurator.isDoSynonyms());
444
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
445
				configurator.isDoNamesWithoutTaxa());
446
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
447
				configurator.isDoTaxaByCommonNames());
448
	}
449

    
450
	/**
451
	 * <p>
452
	 * firePreferencesChanged
453
	 * </p>
454
	 *
455
	 * @param clazz
456
	 *            a {@link java.lang.Class} object.
457
	 */
458
	public static void firePreferencesChanged(Class clazz) {
459
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
460
				null, clazz);
461
	}
462

    
463
	/**
464
	 * Set default values for preferences
465
	 */
466
	public static void setDefaults() {
467
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
468
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
469
				true);
470
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
471
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
472
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
473
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
474
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
475
				"http://www.biodiversitylibrary.org/openurl");
476
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
477
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
478
		getPreferenceStore().setDefault(IPreferenceKeys.DISTRIBUTION_AREA_PREFRENCES_ACTIVE, false);
479
		getPreferenceStore().setDefault(CHECKLIST_ID_IN_VOCABULARY, true);
480
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, true);
481
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE, true);
482
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, true);
483
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_HYBRID, true);
484
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_LSID, true);
485
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, true);
486
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAMECACHE, true);
487
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, true);
488
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, true);
489
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, true);
490
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, true);
491
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_RANK, true);
492
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, true);
493
	}
494

    
495
	/**
496
	 * <p>
497
	 * checkNomenclaturalCode
498
	 * </p>
499
	 */
500
	public static void checkNomenclaturalCode() {
501
		// First time Editor is opened, no nomenclatural code has been set
502

    
503

    
504
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
505
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP, true);
506
		}
507

    
508

    
509

    
510
	}
511
	public static void setNomenclaturalCodePreferences(){
512
	    ICdmRepository controller;
513
        controller = CdmStore.getCurrentApplicationConfiguration();
514
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
515
        CdmPreference preference = null;
516
        if (controller == null){
517
            return ;
518
        }
519
        preference = controller.getPreferenceService().find(key);
520
        if (preference == null){
521
            return;
522
        }
523
        getPreferenceStore().setValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
524

    
525
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
526
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
527
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
528

    
529
        getPreferenceStore().setValue(CDM_NOMENCLATURAL_CODE_KEY,
530
                getPreferenceKey(preferredCode));
531

    
532
        if (!preference.isAllowOverride()){
533
            getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
534
                    getPreferenceKey(preferredCode));
535
        }
536
	}
537

    
538
	public static void checkDefaultLanguage(){
539
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
540
	       Shell shell = AbstractUtility.getShell();
541
	       int open = new DefaultLanguageDialog(shell).open();
542
	       if(open == Window.OK){
543
	           PlatformUI.getWorkbench().restart();
544
	       }
545
	    }else{
546
	        //TODO:In case of a reinstall, the config.ini will be overwritten
547
	        //     here you create config.ini with the stored key from preferences
548
	    }
549
	}
550

    
551
	/**
552
	 * <p>
553
	 * getMapServiceAccessPoint
554
	 * </p>
555
	 *
556
	 * @return a {@link java.lang.String} object.
557
	 */
558
	public static String getMapServiceAccessPoint() {
559
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
560
	}
561

    
562
	/**
563
	 * <p>
564
	 * shouldConnectAtStartUp
565
	 * </p>
566
	 *
567
	 * @return a boolean.
568
	 */
569
	public static boolean shouldConnectAtStartUp() {
570
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
571
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
572
		return false;
573
	}
574

    
575
	/**
576
	 * <p>
577
	 * getDefaultFeatureTreeForTextualDescription
578
	 * </p>
579
	 *
580
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
581
	 */
582
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
583
		String uuidString = getPreferenceStore().getString(
584
				FEATURE_TREE_DEFAULT_TEXT);
585
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
586
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
587
	}
588

    
589
	/**
590
	 * <p>
591
	 * getDefaultFeatureTreeForStructuredDescription
592
	 * </p>
593
	 *
594
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
595
	 */
596
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
597
		String uuidString = getPreferenceStore().getString(
598
				FEATURE_TREE_DEFAULT_STRUCTURE);
599
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
600
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
601
	}
602

    
603
	/**
604
	 * <p>
605
	 * setSortRanksHierarchichally
606
	 * </p>
607
	 *
608
	 * @param selection
609
	 *            a boolean.
610
	 */
611
	public static void setSortRanksHierarchichally(boolean selection) {
612
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
613
	}
614

    
615
	/**
616
	 * <p>
617
	 * getSortRanksHierarchichally
618
	 * </p>
619
	 *
620
	 * @return a boolean.
621
	 */
622
	public static boolean getSortRanksHierarchichally() {
623
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
624
	}
625

    
626
	public static boolean isMultilanguageTextEditingCapability() {
627
		return getPreferenceStore().getBoolean(
628
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
629
	}
630

    
631
	public static Language getGlobalLanguage() {
632

    
633

    
634
		String languageUuidString = getPreferenceStore().getString(
635
				GLOBAL_LANGUAGE_UUID);
636

    
637
		if(!CdmStore.isActive()) {
638
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
639
            return null;
640
        }
641

    
642
		if (CdmUtils.isBlank(languageUuidString)) {
643
			return Language.getDefaultLanguage();
644
		}
645

    
646
		UUID languageUuid = UUID.fromString(languageUuidString);
647
		return (Language) CdmStore.getService(ITermService.class).load(
648
				languageUuid);
649
	}
650

    
651
	public static void setGlobalLanguage(Language language) {
652
	    if(language != null) {
653
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
654
	        CdmStore.setDefaultLanguage(language);
655
	    }
656

    
657
	}
658

    
659
	/**
660
	 * @return
661
	 */
662
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
663
		List<MarkerType> markerTypes = CdmStore.getTermManager()
664
				.getPreferredTerms(MarkerType.class);
665

    
666
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
667

    
668
		for (MarkerType markerType : markerTypes) {
669
			String name = getMarkerTypeEditingPreferenceKey(markerType);
670
			Boolean value = getPreferenceStore().getBoolean(name);
671

    
672
			result.put(markerType, value);
673
		}
674

    
675
		return result;
676
	}
677

    
678
	/**
679
	 * @param markerTypeEditingMap
680
	 */
681
	public static void setEditMarkerTypePreferences(
682
			Map<MarkerType, Boolean> markerTypeEditingMap) {
683
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
684
			String name = getMarkerTypeEditingPreferenceKey(markerType);
685
			getPreferenceStore().setValue(name,
686
					markerTypeEditingMap.get(markerType));
687
		}
688

    
689
	}
690

    
691
	private static String getMarkerTypeEditingPreferenceKey(
692
			MarkerType markerType) {
693
		markerType = HibernateProxyHelper.deproxy(markerType);
694
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
695
	}
696

    
697
	/**
698
	 * <p>
699
	 * setEditMarkerTypePreference
700
	 * </p>
701
	 *
702
	 * @param input
703
	 *            a {@link org.eclipse.ui.IEditorInput} object.
704
	 * @param markerType
705
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
706
	 * @param edit
707
	 *            a boolean.
708
	 */
709
	public static void setEditMarkerTypePreference(MarkerType markerType,
710
			boolean edit) {
711
		getPreferenceStore().setValue(
712
				getMarkerTypeEditingPreferenceKey(markerType), edit);
713
	}
714

    
715
	/**
716
	 * @return
717
	 */
718
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
719
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
720
				.NewInstance();
721
		configurator.setMoveDerivedUnitMediaToGallery(true);
722
		configurator.setMoveFieldObjectMediaToGallery(true);
723
		return configurator;
724
	}
725

    
726
	/**
727
	 * This method will write language properties to the config.ini located in the configuration folder
728
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
729
	 *
730
	 * @param setLanguage 0 is for german and 1 for english.
731
	 * @throws IOException
732
	 */
733
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
734
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
735
        //give warning to user if the directory has no write access
736
        if(file == null){
737
            throw new IOException();
738
        }
739
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
740
        switch(setLanguage){
741
        case 0:
742
            properties.setProperty("osgi.nl", "de");
743
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
744
            break;
745
        case 1:
746
            properties.setProperty("osgi.nl", "en");
747
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
748
            break;
749
        default:
750
            break;
751
        }
752
        save(file+"/config.ini", properties);
753
    }
754

    
755
    /**
756
     * This method loads a property from a given file and returns it.
757
     *
758
     * @param filename
759
     * @return
760
     * @throws IOException
761
     */
762
    private Properties load(String filename) throws IOException {
763
        FileInputStream in = new FileInputStream(filename);
764
        Properties prop = new Properties();
765
        prop.load(in);
766
        in.close();
767
        return prop;
768
    }
769

    
770
    /**
771
     * This method saves a property to the specified file.
772
     *
773
     * @param filename
774
     * @param properties
775
     * @throws IOException
776
     */
777
    private void save(String filename, Properties properties) throws IOException{
778
        FileOutputStream fos =  new FileOutputStream(filename);
779
        properties.store(fos, "");
780
        fos.close();
781
    }
782

    
783
    /**
784
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
785
     *
786
     * @param p2Repos
787
     */
788
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
789
        StringBuilder sb = new StringBuilder();
790
        for(MetadataRepositoryElement p2Repo : p2Repos) {
791
            sb.append(P2_REPOSITORIES_DELIM);
792
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
793
                sb.append("-");
794
            } else {
795
                sb.append(p2Repo.getName());
796
            }
797
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
798
            sb.append(p2Repo.getLocation().toString());
799
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
800
            sb.append(String.valueOf(p2Repo.isEnabled()));
801
        }
802
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
803
    }
804

    
805

    
806
    /**
807
     * Retrieves a list of previously saved P2 repositories
808
     *
809
     * @return
810
     */
811
    public static List<MetadataRepositoryElement> getP2Repositories() {
812
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
813
        String p2ReposPref =  getPreferenceStore().getString(P2_REPOSITORY_LIST);
814
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
815
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
816

    
817
            while(p2ReposPrefST.hasMoreTokens()) {
818
                String p2RepoStr = p2ReposPrefST.nextToken();
819
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
820
                if(p2ReposStrST.countTokens()==3) {
821
                    String nickname = p2ReposStrST.nextToken();
822
                    URI uri = null;
823
                    try {
824
                        uri = new URI(p2ReposStrST.nextToken());
825
                    } catch (URISyntaxException e) {
826
                        continue;
827
                    }
828
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
829
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
830
                    mre.setNickname(nickname);
831
                    mre.setEnabled(enabled);
832
                    p2Repos.add(mre);
833
                }
834
            }
835
        }
836

    
837
        return p2Repos;
838
    }
839

    
840
    /**
841
     * enables/disables nested composite. <br>
842
     *
843
     * @param ctrl - Composite to be en-/disabeld
844
     * @param enabled - boolean
845
     */
846
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
847
        if (ctrl instanceof Composite) {
848
            Composite comp = (Composite) ctrl;
849
            for (Control c : comp.getChildren()) {
850
                recursiveSetEnabled(c, enabled);
851
            }
852
        } else {
853
            ctrl.setEnabled(enabled);
854
        }
855
    }
856

    
857
    /**
858
	 * <p>
859
	 * getSortRanksNaturally
860
	 * </p>
861
	 *
862
	 * @return a boolean.
863
	 */
864
	public static boolean getSortNodesNaturally() {
865
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
866
	}
867

    
868
	/**
869
	 * <p>
870
	 * setSortRanksNaturally
871
	 * </p>
872
	 *
873
	 * @param selection
874
	 *            a boolean.
875
	 */
876
	public static void setSortNodesNaturally(boolean selection) {
877
		getPreferenceStore().setValue(SORT_NODES_NATURALLY, selection);
878
	}
879

    
880

    
881
	/**
882
	 * <p>
883
	 * getSortRanksNaturally
884
	 * </p>
885
	 *
886
	 * @return a boolean.
887
	 */
888
	public static boolean getSortNodesStrictlyAlphabetically() {
889
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
890
	}
891

    
892
	/**
893
	 * <p>
894
	 * setSortRanksNaturally
895
	 * </p>
896
	 *
897
	 * @param selection
898
	 *            a boolean.
899
	 */
900
	public static void setSortNodesStrictlyAlphabetically(boolean selection) {
901
		getPreferenceStore().setValue(SORT_NODES_ALPHABETICALLY, selection);
902
	}
903

    
904
	/**
905
	 * <p>
906
	 * setStoreNavigatorState
907
	 * </p>
908
	 *
909
	 * @param selection
910
	 *            a boolean.
911
	 */
912
	public static boolean isStoreNavigatorState() {
913
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
914

    
915
	}
916

    
917
	/**
918
	 * <p>
919
	 * setStoreNavigatorState
920
	 * </p>
921
	 *
922
	 * @param selection
923
	 *            a boolean.
924
	 */
925
	public static void setStoreNavigatorState(boolean selection) {
926
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
927

    
928
	}
929

    
930
    /**
931
     * @return
932
     */
933
    public static boolean isShowUpWidgetIsDisposedMessages() {
934
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
935
    }
936
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
937
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
938
    }
939

    
940
    /**
941
     * @return
942
     */
943
    public static boolean isShowIdInVocabularyInChecklistEditor() {
944
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
945
    }
946
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
947
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
948
    }
949

    
950
    /**
951
     * @return
952
     */
953
    public static boolean isShowRankInChecklistEditor() {
954
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
955
    }
956
    public static void setShowRankInChecklistEditor(boolean selection) {
957
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
958
    }
959

    
960
    /**
961
     * @param object
962
     * @param b
963
     * @return
964
     */
965
    public static NameDetailsConfigurator setPreferredNameDetailsConfiguration( boolean local) {
966
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
967

    
968
        CdmPreference preference = null;
969

    
970
        if (!local) {
971
            preference = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
972
        }
973
        if (preference == null){
974
            return null;
975
        }
976

    
977
        getPreferenceStore().setValue(ALLOW_OVERRIDE_NAMEDETAILS, preference.isAllowOverride());
978

    
979
        //the preference value is build like this:
980
        //<section1>:true;<section2>:false....
981

    
982
        String value = preference.getValue();
983
        String [] sections = value.split(";");
984
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
985
        String[] sectionValues;
986
        for (String sectionValue: sections){
987
            sectionValues = sectionValue.split(":");
988
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
989
        }
990

    
991

    
992

    
993
        getPreferenceStore().setValue(SHOW_SIMPLE_NAME_DETAILS_TAXON,
994
                (sectionMap.get("taxon")));
995
        config.setTaxonSectionActivated(sectionMap.get("taxon"));
996

    
997
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_LSID,
998
                (sectionMap.get("lsid")));
999
        config.setLSIDActivated(sectionMap.get("lsid"));
1000

    
1001
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1002
                (sectionMap.get("nc")));
1003
        config.setNomenclaturalCodeActived(sectionMap.get("nc"));
1004

    
1005
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1006
                (sectionMap.get("ap")));
1007
        config.setAppendedPhraseActivated(sectionMap.get("ap"));
1008

    
1009
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_RANK,
1010
                (sectionMap.get("rank")));
1011
        config.setRankActivated(sectionMap.get("rank"));
1012

    
1013

    
1014
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1015
                (sectionMap.get("atomisedEpithets")));
1016
        config.setAtomisedEpithetsActivated(sectionMap.get("atomisedEpithets"));
1017

    
1018
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1019
                (sectionMap.get("author")));
1020
        config.setAuthorshipSectionActivated(sectionMap.get("author"));
1021

    
1022
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1023
                (sectionMap.get("nomRef")));
1024
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1025

    
1026
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1027
                (sectionMap.get("nomStat")));
1028
        config.setNomenclaturalStatusSectionActivated(sectionMap.get("nomStat"));
1029

    
1030

    
1031
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1032
                (sectionMap.get("protologue")));
1033
        config.setProtologueActivated(sectionMap.get("protologue"));
1034

    
1035
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1036
                (sectionMap.get("typeDes")));
1037
        config.setTypeDesignationSectionActivated(sectionMap.get("typeDes"));
1038

    
1039
        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1040
                (sectionMap.get("nameRelation")));
1041
        config.setNameRelationsSectionActivated(sectionMap.get("nameRelation"));
1042

    
1043
        return config;
1044
    }
1045

    
1046
    public static boolean getIsDeterminiationOnlyForFieldUnit(boolean local){
1047
        CdmPreference preference = null;
1048

    
1049
        if (!local) {
1050
            preference = getPreferenceFromDB(PreferencePredicate.DeterminationOnlyForFieldUnits);
1051
        }
1052
        if (preference == null){
1053
            return getPreferenceStore().getBoolean(DETERMINATION_ONLY_FOR_FIELD_UNITS);
1054
        }
1055
        return Boolean.valueOf(preference.getValue());
1056
    }
1057

    
1058
    public static boolean getIsShowCollectingAreasInGeneralSection(boolean local){
1059
        CdmPreference preference = null;
1060

    
1061
        if (!local) {
1062
            preference = getPreferenceFromDB(PreferencePredicate.ShowCollectingAreasInGeneralSection);
1063
        }
1064
        if (preference == null){
1065
            return getPreferenceStore().getBoolean(SHOW_COLLECTING_AREAS_IN_GENERAL_SECTION);
1066
        }
1067
        return Boolean.valueOf(preference.getValue());
1068
    }
1069

    
1070
    public static boolean getIsShowTaxonAssociations(boolean local){
1071
        CdmPreference preference = null;
1072

    
1073
        if (!local) {
1074
            preference = getPreferenceFromDB(PreferencePredicate.ShowTaxonAssociations);
1075
        }
1076
        if (preference == null){
1077
            return getPreferenceStore().getBoolean(SHOW_TAXON_ASSOCIATIONS);
1078
        }
1079
        return Boolean.valueOf(preference.getValue());
1080
    }
1081

    
1082

    
1083

    
1084

    
1085
}
(21-21/26)