Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.net.URI;
17
import java.net.URISyntaxException;
18
import java.util.ArrayList;
19
import java.util.Arrays;
20
import java.util.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.ICdmApplicationConfiguration;
38
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
39
import eu.etaxonomy.cdm.api.service.IFeatureTreeService;
40
import eu.etaxonomy.cdm.api.service.IPreferenceService;
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.model.common.ICdmBase;
47
import eu.etaxonomy.cdm.model.common.IDefinedTerm;
48
import eu.etaxonomy.cdm.model.common.ISimpleTerm;
49
import eu.etaxonomy.cdm.model.common.Language;
50
import eu.etaxonomy.cdm.model.common.MarkerType;
51
import eu.etaxonomy.cdm.model.common.TermBase;
52
import eu.etaxonomy.cdm.model.description.FeatureTree;
53
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
54
import eu.etaxonomy.cdm.model.metadata.CdmPreference.PrefKey;
55
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
56
import eu.etaxonomy.cdm.model.metadata.PreferenceSubject;
57
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
58
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
59
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
60
import eu.etaxonomy.cdm.strategy.match.MatchException;
61
import eu.etaxonomy.cdm.strategy.match.MatchMode;
62
import eu.etaxonomy.taxeditor.model.AbstractUtility;
63
import eu.etaxonomy.taxeditor.model.MessagingUtils;
64
import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
65
import eu.etaxonomy.taxeditor.store.CdmStore;
66
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
67
import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
68

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

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

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

    
89

    
90

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

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

    
139
	public static NomenclaturalCode getPreferredNomenclaturalCode(){
140
		return getPreferredNomenclaturalCode(false);
141
	}
142
	
143
	/**
144
	 * <p>
145
	 * getPreferredNomenclaturalCode
146
	 * </p>
147
	 *
148
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
149
	 */
150
	public static NomenclaturalCode getPreferredNomenclaturalCode(boolean preConnected) {
151
		ICdmApplicationConfiguration controller;
152
		CdmPreference pref = null;
153
		if (!preConnected){
154
			try{
155
				controller = CdmStore.getCurrentApplicationConfiguration();
156
				PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
157
			    pref = controller.getPreferenceService().find(key);
158
			}catch(Exception e){
159
				e.printStackTrace();
160
			}
161
		}
162
		
163
	    String preferredCode;
164
	    if(pref == null){
165
	    	preferredCode = getPreferenceStore().getString(
166
					PREFERRED_NOMENCLATURAL_CODE_KEY);
167
	    }else{
168
	    	preferredCode = pref.getValue();
169
	    }
170
	    
171
		for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
172
//			String preferredCode = getPreferenceStore().getString(
173
//					PREFERRED_NOMENCLATURAL_CODE_KEY);
174
			if (getPreferenceKey(code).equals(preferredCode)) {
175
				return code;
176
			}
177
		}
178
		return null;
179
	}
180

    
181
	public static String getPreferredDefaultLangugae(){
182
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
183
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
184
	        return preferredLanguage;
185
	    }
186
	    return null;
187
	}
188

    
189
	/**
190
	 * Get the match strategy for the given class that was stored in preferences
191
	 * or the default strategy if it was not stored in preferences
192
	 *
193
	 * @param clazz
194
	 *            a {@link java.lang.Class} object.
195
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
196
	 */
197
	public static IMatchStrategy getMatchStrategy(Class clazz) {
198
		String className = clazz.getName();
199
		if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
200
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
201

    
202
			for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
203
				String matchModeName = getPreferenceStore().getString(
204
						getMatchStrategyFieldName(className, fieldName));
205
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
206
				try {
207
					matchStrategy.setMatchMode(fieldName, matchMode);
208
				} catch (MatchException e) {
209
					MessagingUtils.error(PreferencesUtil.class, e);
210
					throw new RuntimeException(e);
211
				}
212
			}
213

    
214
			return matchStrategy;
215
		}
216
		return getDefaultMatchStrategy(clazz);
217
	}
218

    
219
	/**
220
	 * Stores a matchStrategy into the preference store.
221
	 *
222
	 * @param matchStrategy
223
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
224
	 *            object.
225
	 */
226
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
227
		String className = matchStrategy.getMatchClass().getName();
228
		getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
229

    
230
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
231

    
232
		for (String fieldName : matchFields) {
233
			getPreferenceStore().setValue(
234
					getMatchStrategyFieldName(className, fieldName),
235
					matchStrategy.getMatchMode(fieldName).name());
236
		}
237
	}
238

    
239
	/**
240
	 * Helper method to create the preference property for a match field.
241
	 *
242
	 * @param className
243
	 * @param fieldName
244
	 * @return
245
	 */
246
	private static String getMatchStrategyFieldName(String className,
247
			String fieldName) {
248
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
249
	}
250

    
251
	/**
252
	 * Returns the default match strategy for a given class.
253
	 *
254
	 * @param clazz
255
	 *            a {@link java.lang.Class} object.
256
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
257
	 */
258
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
259
		return DefaultMatchStrategy.NewInstance(clazz);
260
	}
261

    
262
	/**
263
	 * <p>
264
	 * getDateFormatPattern
265
	 * </p>
266
	 *
267
	 * @return a {@link java.lang.String} object.
268
	 */
269
	public static String getDateFormatPattern() {
270
		// TODO make this configurable in properties
271
		String pattern = "Y-M-d H:m";
272
		return pattern;
273
	}
274

    
275
	/**
276
	 * <p>
277
	 * addTermToPreferredTerms
278
	 * </p>
279
	 *
280
	 * @param term
281
	 *            a T object.
282
	 * @param <T>
283
	 *            a T object.
284
	 */
285
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
286

    
287
		// VocabularyEnum vocabulary =
288
		// VocabularyEnum.getVocabularyEnum(term.getClass());
289
		//
290
		// getPreferenceStore().setValue(getPreferenceKey(term),
291
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
292
		//
293
		// firePreferencesChanged(term.getClass());
294
	}
295

    
296
	/**
297
	 * Construct a unique key using the CdmBase object's uuid
298
	 *
299
	 * @param cdmBase
300
	 * @return
301
	 */
302
	private static String getPreferenceKey(ICdmBase cdmBase) {
303
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
304

    
305
		String key = cdmBase.getClass().getName().concat(".")
306
				.concat(cdmBase.getUuid().toString());
307
		if (key.contains("javassist")) {
308
			MessagingUtils.info("proxy");
309
		}
310
		return key;
311
	}
312

    
313
	/**
314
	 * Construct a unique key using the CdmBase object's uuid
315
	 *
316
	 * @param cdmBase
317
	 * @return
318
	 */
319
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
320
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
321
		String key = simpleTerm.getClass().getName().concat(".")
322
				.concat(simpleTerm.getUuid().toString());
323
		if (key.contains("javassist")) {
324
			MessagingUtils.warn(PreferencesUtil.class,
325
					"Trying to persist a preference based on a proxy class.");
326
		}
327
		return key;
328
	}
329

    
330

    
331

    
332
	/**
333
	 * Construct a unique key using the CdmBase object's uuid
334
	 *
335
	 * @param cdmBase
336
	 * @return
337
	 */
338
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
339
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
340
		String key = definedTerm.getClass().getName().concat(".")
341
				.concat(definedTerm.getUuid().toString());
342
		if (key.contains("javassist")) {
343
			MessagingUtils.warn(PreferencesUtil.class,
344
					"Trying to persist a preference based on a proxy class.");
345
		}
346
		return key;
347
	}
348

    
349
	/**
350
	 * Retrieves search preferences from the preference store
351
	 *
352
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
353
	 */
354
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
355
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
356

    
357
		configurator.setDoTaxa(getPreferenceStore().getBoolean(
358
				TAXON_SERVICE_CONFIGURATOR_TAXA));
359
		configurator.setDoSynonyms(getPreferenceStore().getBoolean(
360
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
361
		configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
362
				TAXON_SERVICE_CONFIGURATOR_NAMES));
363
		configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
364
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
365
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getPreferenceStore().getString(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
366

    
367
		return configurator;
368
	}
369

    
370
	/**
371
	 * create new preferences, setting all search options to true
372
	 *
373
	 * @return a
374
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
375
	 *         object.
376
	 */
377
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
378
		IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
379

    
380
		configurator.setDoTaxa(true);
381
		configurator.setDoSynonyms(true);
382
		configurator.setDoNamesWithoutTaxa(true);
383
		configurator.setDoTaxaByCommonNames(true);
384

    
385
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
386
				"name", "name.$", "relationsFromThisTaxon.$"));
387

    
388
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
389
				"name", "name.$", "synonymRelations.relatedTo.*"));
390

    
391
		// DEFAULT VALUES
392
		// match mode is a simple like, actually all other match modes are kind
393
		// of bogus
394
		configurator
395
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
396
		// we set page number and size here as this should always be unlimited
397
		configurator.setPageNumber(0);
398
		// TODO currently limit results to 10000
399
		configurator.setPageSize(10000);
400

    
401
		return configurator;
402
	}
403

    
404
	/**
405
	 * Store search preferences
406
	 *
407
	 * @param configurator
408
	 *            a
409
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
410
	 *            object.
411
	 */
412
	public static void setSearchConfigurator(
413
			IFindTaxaAndNamesConfigurator configurator) {
414
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
415
				configurator.isDoTaxa());
416
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
417
				configurator.isDoSynonyms());
418
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
419
				configurator.isDoNamesWithoutTaxa());
420
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
421
				configurator.isDoTaxaByCommonNames());
422
	}
423

    
424
	/**
425
	 * <p>
426
	 * firePreferencesChanged
427
	 * </p>
428
	 *
429
	 * @param clazz
430
	 *            a {@link java.lang.Class} object.
431
	 */
432
	public static void firePreferencesChanged(Class clazz) {
433
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
434
				null, clazz);
435
	}
436

    
437
	/**
438
	 * Set default values for preferences
439
	 */
440
	public static void setDefaults() {
441
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
442
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
443
				true);
444
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
445
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
446
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
447
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
448
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
449
				"http://www.biodiversitylibrary.org/openurl");
450
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
451
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
452
		getPreferenceStore().setDefault(IPreferenceKeys.DISTRIBUTION_AREA_PREFRENCES_ACTIVE, false);
453
		getPreferenceStore().setDefault(CHECKLIST_ID_IN_VOCABULARY, true);
454
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, true);
455
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, true);
456
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_HYBRID, true);
457
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_LSID, true);
458
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, true);
459
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NAMECACHE, true);
460
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, true);
461
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, true);
462
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, true);
463
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, true);
464
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_RANK, true);
465
		getPreferenceStore().setDefault(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, true);
466
	}
467

    
468
	/**
469
	 * <p>
470
	 * checkNomenclaturalCode
471
	 * </p>
472
	 */
473
	public static void checkNomenclaturalCode() {
474
		// First time Editor is opened, no nomenclatural code has been set
475

    
476

    
477
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
478
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
479
			/*
480

    
481
			StoreUtil.info("No nomencatural code set.");
482

    
483
			Shell shell = StoreUtil.getShell();
484

    
485
		 Query user re: preferred nom. code
486
			Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
487
			dialog.open();
488

    
489
			// Short message confirming user's choice
490
			NomenclaturalCode code = PreferencesUtil
491
					.getPreferredNomenclaturalCode();
492
			MessageDialog
493
					.openInformation(
494
							shell,
495
							"Nomenclatural code set",
496
							"The following has been set as your preferred nomenclatural code:\n\n\t"
497
									+ NomenclaturalCodeHelper
498
											.getDescription(code)
499
									+ "\n\nYou can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
500
		}
501
	}
502

    
503
	public static void checkDefaultLanguage(){
504
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
505
	       Shell shell = AbstractUtility.getShell();
506
	       int open = new DefaultLanguageDialog(shell).open();
507
	       if(open == Window.OK){
508
	           PlatformUI.getWorkbench().restart();
509
	       }
510
	    }else{
511
	        //TODO:In case of a reinstall, the config.ini will be overwritten
512
	        //     here you create config.ini with the stored key from preferences
513
	    }
514
	}
515

    
516
	/**
517
	 * <p>
518
	 * getMapServiceAccessPoint
519
	 * </p>
520
	 *
521
	 * @return a {@link java.lang.String} object.
522
	 */
523
	public static String getMapServiceAccessPoint() {
524
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
525
	}
526

    
527
	/**
528
	 * <p>
529
	 * shouldConnectAtStartUp
530
	 * </p>
531
	 *
532
	 * @return a boolean.
533
	 */
534
	public static boolean shouldConnectAtStartUp() {
535
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
536
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
537
		return false;
538
	}
539

    
540
	/**
541
	 * <p>
542
	 * getDefaultFeatureTreeForTextualDescription
543
	 * </p>
544
	 *
545
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
546
	 */
547
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
548
		String uuidString = getPreferenceStore().getString(
549
				FEATURE_TREE_DEFAULT_TEXT);
550
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
551
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
552
	}
553

    
554
	/**
555
	 * <p>
556
	 * getDefaultFeatureTreeForStructuredDescription
557
	 * </p>
558
	 *
559
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
560
	 */
561
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
562
		String uuidString = getPreferenceStore().getString(
563
				FEATURE_TREE_DEFAULT_STRUCTURE);
564
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
565
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
566
	}
567

    
568
	/**
569
	 * <p>
570
	 * setSortRanksHierarchichally
571
	 * </p>
572
	 *
573
	 * @param selection
574
	 *            a boolean.
575
	 */
576
	public static void setSortRanksHierarchichally(boolean selection) {
577
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
578
	}
579

    
580
	/**
581
	 * <p>
582
	 * getSortRanksHierarchichally
583
	 * </p>
584
	 *
585
	 * @return a boolean.
586
	 */
587
	public static boolean getSortRanksHierarchichally() {
588
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
589
	}
590

    
591
	public static boolean isMultilanguageTextEditingCapability() {
592
		return getPreferenceStore().getBoolean(
593
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
594
	}
595

    
596
	public static Language getGlobalLanguage() {
597

    
598

    
599
		String languageUuidString = getPreferenceStore().getString(
600
				GLOBAL_LANGUAGE_UUID);
601

    
602
		if(!CdmStore.isActive()) {
603
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
604
            return null;
605
        }
606

    
607
		if (CdmUtils.isBlank(languageUuidString)) {
608
			return Language.getDefaultLanguage();
609
		}
610

    
611
		UUID languageUuid = UUID.fromString(languageUuidString);
612
		return (Language) CdmStore.getService(ITermService.class).load(
613
				languageUuid);
614
	}
615

    
616
	public static void setGlobalLanguage(Language language) {
617
	    if(language != null) {
618
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
619
	        CdmStore.setDefaultLanguage(language);
620
	    }
621

    
622
	}
623

    
624
	/**
625
	 * @return
626
	 */
627
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
628
		List<MarkerType> markerTypes = CdmStore.getTermManager()
629
				.getPreferredTerms(MarkerType.class);
630

    
631
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
632

    
633
		for (MarkerType markerType : markerTypes) {
634
			String name = getMarkerTypeEditingPreferenceKey(markerType);
635
			Boolean value = getPreferenceStore().getBoolean(name);
636

    
637
			result.put(markerType, value);
638
		}
639

    
640
		return result;
641
	}
642

    
643
	/**
644
	 * @param markerTypeEditingMap
645
	 */
646
	public static void setEditMarkerTypePreferences(
647
			Map<MarkerType, Boolean> markerTypeEditingMap) {
648
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
649
			String name = getMarkerTypeEditingPreferenceKey(markerType);
650
			getPreferenceStore().setValue(name,
651
					markerTypeEditingMap.get(markerType));
652
		}
653

    
654
	}
655

    
656
	private static String getMarkerTypeEditingPreferenceKey(
657
			MarkerType markerType) {
658
		markerType = HibernateProxyHelper.deproxy(markerType);
659
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
660
	}
661

    
662
	/**
663
	 * <p>
664
	 * setEditMarkerTypePreference
665
	 * </p>
666
	 *
667
	 * @param input
668
	 *            a {@link org.eclipse.ui.IEditorInput} object.
669
	 * @param markerType
670
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
671
	 * @param edit
672
	 *            a boolean.
673
	 */
674
	public static void setEditMarkerTypePreference(MarkerType markerType,
675
			boolean edit) {
676
		getPreferenceStore().setValue(
677
				getMarkerTypeEditingPreferenceKey(markerType), edit);
678
	}
679

    
680
	/**
681
	 * @return
682
	 */
683
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
684
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
685
				.NewInstance();
686
		configurator.setMoveDerivedUnitMediaToGallery(true);
687
		configurator.setMoveFieldObjectMediaToGallery(true);
688
		return configurator;
689
	}
690

    
691
	/**
692
	 * This method will write language properties to the config.ini located in the configuration folder
693
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
694
	 *
695
	 * @param setLanguage 0 is for german and 1 for english.
696
	 * @throws IOException
697
	 */
698
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
699
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
700
        //give warning to user if the directory has no write access
701
        if(file == null){
702
            throw new IOException();
703
        }
704
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
705
        switch(setLanguage){
706
        case 0:
707
            properties.setProperty("osgi.nl", "de");
708
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
709
            break;
710
        case 1:
711
            properties.setProperty("osgi.nl", "en");
712
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
713
            break;
714
        default:
715
            break;
716
        }
717
        save(file+"/config.ini", properties);
718
    }
719

    
720
    /**
721
     * This method loads a property from a given file and returns it.
722
     *
723
     * @param filename
724
     * @return
725
     * @throws IOException
726
     */
727
    private Properties load(String filename) throws IOException {
728
        FileInputStream in = new FileInputStream(filename);
729
        Properties prop = new Properties();
730
        prop.load(in);
731
        in.close();
732
        return prop;
733
    }
734

    
735
    /**
736
     * This method saves a property to the specified file.
737
     *
738
     * @param filename
739
     * @param properties
740
     * @throws IOException
741
     */
742
    private void save(String filename, Properties properties) throws IOException{
743
        FileOutputStream fos =  new FileOutputStream(filename);
744
        properties.store(fos, "");
745
        fos.close();
746
    }
747

    
748
    /**
749
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
750
     *
751
     * @param p2Repos
752
     */
753
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
754
        StringBuilder sb = new StringBuilder();
755
        for(MetadataRepositoryElement p2Repo : p2Repos) {
756
            sb.append(P2_REPOSITORIES_DELIM);
757
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
758
                sb.append("-");
759
            } else {
760
                sb.append(p2Repo.getName());
761
            }
762
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
763
            sb.append(p2Repo.getLocation().toString());
764
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
765
            sb.append(String.valueOf(p2Repo.isEnabled()));
766
        }
767
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
768
    }
769

    
770

    
771
    /**
772
     * Retrieves a list of previously saved P2 repositories
773
     *
774
     * @return
775
     */
776
    public static List<MetadataRepositoryElement> getP2Repositories() {
777
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
778
        String p2ReposPref =  getPreferenceStore().getString(P2_REPOSITORY_LIST);
779
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
780
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
781

    
782
            while(p2ReposPrefST.hasMoreTokens()) {
783
                String p2RepoStr = p2ReposPrefST.nextToken();
784
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
785
                if(p2ReposStrST.countTokens()==3) {
786
                    String nickname = p2ReposStrST.nextToken();
787
                    URI uri = null;
788
                    try {
789
                        uri = new URI(p2ReposStrST.nextToken());
790
                    } catch (URISyntaxException e) {
791
                        continue;
792
                    }
793
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
794
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
795
                    mre.setNickname(nickname);
796
                    mre.setEnabled(enabled);
797
                    p2Repos.add(mre);
798
                }
799
            }
800
        }
801

    
802
        return p2Repos;
803
    }
804

    
805
    /**
806
     * enables/disables nested composite. <br>
807
     *
808
     * @param ctrl - Composite to be en-/disabeld
809
     * @param enabled - boolean
810
     */
811
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
812
        if (ctrl instanceof Composite) {
813
            Composite comp = (Composite) ctrl;
814
            for (Control c : comp.getChildren()) {
815
                recursiveSetEnabled(c, enabled);
816
            }
817
        } else {
818
            ctrl.setEnabled(enabled);
819
        }
820
    }
821

    
822
    /**
823
	 * <p>
824
	 * getSortRanksNaturally
825
	 * </p>
826
	 *
827
	 * @return a boolean.
828
	 */
829
	public static boolean getSortNodesNaturally() {
830
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
831
	}
832

    
833
	/**
834
	 * <p>
835
	 * setSortRanksNaturally
836
	 * </p>
837
	 *
838
	 * @param selection
839
	 *            a boolean.
840
	 */
841
	public static void setSortNodesNaturally(boolean selection) {
842
		getPreferenceStore().setValue(SORT_NODES_NATURALLY, selection);
843
	}
844

    
845

    
846
	/**
847
	 * <p>
848
	 * getSortRanksNaturally
849
	 * </p>
850
	 *
851
	 * @return a boolean.
852
	 */
853
	public static boolean getSortNodesStrictlyAlphabetically() {
854
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
855
	}
856

    
857
	/**
858
	 * <p>
859
	 * setSortRanksNaturally
860
	 * </p>
861
	 *
862
	 * @param selection
863
	 *            a boolean.
864
	 */
865
	public static void setSortNodesStrictlyAlphabetically(boolean selection) {
866
		getPreferenceStore().setValue(SORT_NODES_ALPHABETICALLY, selection);
867
	}
868

    
869
	/**
870
	 * <p>
871
	 * setStoreNavigatorState
872
	 * </p>
873
	 *
874
	 * @param selection
875
	 *            a boolean.
876
	 */
877
	public static boolean isStoreNavigatorState() {
878
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
879

    
880
	}
881

    
882
	/**
883
	 * <p>
884
	 * setStoreNavigatorState
885
	 * </p>
886
	 *
887
	 * @param selection
888
	 *            a boolean.
889
	 */
890
	public static void setStoreNavigatorState(boolean selection) {
891
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
892

    
893
	}
894

    
895
    /**
896
     * @return
897
     */
898
    public static boolean isShowUpWidgetIsDisposedMessages() {
899
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
900
    }
901
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
902
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
903
    }
904

    
905
    /**
906
     * @return
907
     */
908
    public static boolean isShowIdInVocabularyInChecklistEditor() {
909
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
910
    }
911
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
912
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
913
    }
914

    
915
    /**
916
     * @return
917
     */
918
    public static boolean isShowRankInChecklistEditor() {
919
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
920
    }
921
    public static void setShowRankInChecklistEditor(boolean selection) {
922
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
923
    }
924

    
925
}
(19-19/25)