Project

General

Profile

Download (27.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 (preferredCode == null){
118
			preference = controller.getPreferenceService().find(key);
119
			if (preference == null){
120
				return;
121
			} else{
122
				int index = StringUtils.lastIndexOf(preference.getValue(), ".");
123
				UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
124
				preferredCode = NomenclaturalCode.getByUuid(uuid);
125
			}
126
		} else{
127
			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferredCode.getKey());
128
			controller.getPreferenceService().set(preference);
129
		}
130
		 
131
	    
132
		getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
133
	    			getPreferenceKey(preferredCode));
134
	}
135

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

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

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

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

    
211
			return matchStrategy;
212
		}
213
		return getDefaultMatchStrategy(clazz);
214
	}
215

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

    
227
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
228

    
229
		for (String fieldName : matchFields) {
230
			getPreferenceStore().setValue(
231
					getMatchStrategyFieldName(className, fieldName),
232
					matchStrategy.getMatchMode(fieldName).name());
233
		}
234
	}
235

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

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

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

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

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

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

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

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

    
327

    
328

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

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

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

    
364
		return configurator;
365
	}
366

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

    
377
		configurator.setDoTaxa(true);
378
		configurator.setDoSynonyms(true);
379
		configurator.setDoNamesWithoutTaxa(true);
380
		configurator.setDoTaxaByCommonNames(true);
381

    
382
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
383
				"name", "name.$", "relationsFromThisTaxon.$"));
384

    
385
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
386
				"name", "name.$", "synonymRelations.relatedTo.*"));
387

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

    
398
		return configurator;
399
	}
400

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

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

    
434
	/**
435
	 * Set default values for preferences
436
	 */
437
	public static void setDefaults() {
438
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
439
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
440
				true);
441
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
442
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
443
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
444
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
445
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
446
				"http://www.biodiversitylibrary.org/openurl");
447
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
448
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
449
		getPreferenceStore().setDefault(IPreferenceKeys.DISTRIBUTION_AREA_PREFRENCES_ACTIVE, false);
450
		getPreferenceStore().setDefault(CHECKLIST_ID_IN_VOCABULARY, true);
451
	}
452

    
453
	/**
454
	 * <p>
455
	 * checkNomenclaturalCode
456
	 * </p>
457
	 */
458
	public static void checkNomenclaturalCode() {
459
		// First time Editor is opened, no nomenclatural code has been set
460

    
461

    
462
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
463
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
464
			/*
465

    
466
			StoreUtil.info("No nomencatural code set.");
467

    
468
			Shell shell = StoreUtil.getShell();
469

    
470
		 Query user re: preferred nom. code
471
			Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
472
			dialog.open();
473

    
474
			// Short message confirming user's choice
475
			NomenclaturalCode code = PreferencesUtil
476
					.getPreferredNomenclaturalCode();
477
			MessageDialog
478
					.openInformation(
479
							shell,
480
							"Nomenclatural code set",
481
							"The following has been set as your preferred nomenclatural code:\n\n\t"
482
									+ NomenclaturalCodeHelper
483
											.getDescription(code)
484
									+ "\n\nYou can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
485
		}
486
	}
487

    
488
	public static void checkDefaultLanguage(){
489
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
490
	       Shell shell = AbstractUtility.getShell();
491
	       int open = new DefaultLanguageDialog(shell).open();
492
	       if(open == Window.OK){
493
	           PlatformUI.getWorkbench().restart();
494
	       }
495
	    }else{
496
	        //TODO:In case of a reinstall, the config.ini will be overwritten
497
	        //     here you create config.ini with the stored key from preferences
498
	    }
499
	}
500

    
501
	/**
502
	 * <p>
503
	 * getMapServiceAccessPoint
504
	 * </p>
505
	 *
506
	 * @return a {@link java.lang.String} object.
507
	 */
508
	public static String getMapServiceAccessPoint() {
509
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
510
	}
511

    
512
	/**
513
	 * <p>
514
	 * shouldConnectAtStartUp
515
	 * </p>
516
	 *
517
	 * @return a boolean.
518
	 */
519
	public static boolean shouldConnectAtStartUp() {
520
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
521
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
522
		return false;
523
	}
524

    
525
	/**
526
	 * <p>
527
	 * getDefaultFeatureTreeForTextualDescription
528
	 * </p>
529
	 *
530
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
531
	 */
532
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
533
		String uuidString = getPreferenceStore().getString(
534
				FEATURE_TREE_DEFAULT_TEXT);
535
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
536
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
537
	}
538

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

    
553
	/**
554
	 * <p>
555
	 * setSortRanksHierarchichally
556
	 * </p>
557
	 *
558
	 * @param selection
559
	 *            a boolean.
560
	 */
561
	public static void setSortRanksHierarchichally(boolean selection) {
562
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
563
	}
564

    
565
	/**
566
	 * <p>
567
	 * getSortRanksHierarchichally
568
	 * </p>
569
	 *
570
	 * @return a boolean.
571
	 */
572
	public static boolean getSortRanksHierarchichally() {
573
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
574
	}
575

    
576
	public static boolean isMultilanguageTextEditingCapability() {
577
		return getPreferenceStore().getBoolean(
578
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
579
	}
580

    
581
	public static Language getGlobalLanguage() {
582

    
583

    
584
		String languageUuidString = getPreferenceStore().getString(
585
				GLOBAL_LANGUAGE_UUID);
586

    
587
		if(!CdmStore.isActive()) {
588
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
589
            return null;
590
        }
591

    
592
		if (CdmUtils.isBlank(languageUuidString)) {
593
			return Language.getDefaultLanguage();
594
		}
595

    
596
		UUID languageUuid = UUID.fromString(languageUuidString);
597
		return (Language) CdmStore.getService(ITermService.class).load(
598
				languageUuid);
599
	}
600

    
601
	public static void setGlobalLanguage(Language language) {
602
	    if(language != null) {
603
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
604
	        CdmStore.setDefaultLanguage(language);
605
	    }
606

    
607
	}
608

    
609
	/**
610
	 * @return
611
	 */
612
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
613
		List<MarkerType> markerTypes = CdmStore.getTermManager()
614
				.getPreferredTerms(MarkerType.class);
615

    
616
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
617

    
618
		for (MarkerType markerType : markerTypes) {
619
			String name = getMarkerTypeEditingPreferenceKey(markerType);
620
			Boolean value = getPreferenceStore().getBoolean(name);
621

    
622
			result.put(markerType, value);
623
		}
624

    
625
		return result;
626
	}
627

    
628
	/**
629
	 * @param markerTypeEditingMap
630
	 */
631
	public static void setEditMarkerTypePreferences(
632
			Map<MarkerType, Boolean> markerTypeEditingMap) {
633
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
634
			String name = getMarkerTypeEditingPreferenceKey(markerType);
635
			getPreferenceStore().setValue(name,
636
					markerTypeEditingMap.get(markerType));
637
		}
638

    
639
	}
640

    
641
	private static String getMarkerTypeEditingPreferenceKey(
642
			MarkerType markerType) {
643
		markerType = HibernateProxyHelper.deproxy(markerType);
644
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
645
	}
646

    
647
	/**
648
	 * <p>
649
	 * setEditMarkerTypePreference
650
	 * </p>
651
	 *
652
	 * @param input
653
	 *            a {@link org.eclipse.ui.IEditorInput} object.
654
	 * @param markerType
655
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
656
	 * @param edit
657
	 *            a boolean.
658
	 */
659
	public static void setEditMarkerTypePreference(MarkerType markerType,
660
			boolean edit) {
661
		getPreferenceStore().setValue(
662
				getMarkerTypeEditingPreferenceKey(markerType), edit);
663
	}
664

    
665
	/**
666
	 * @return
667
	 */
668
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
669
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
670
				.NewInstance();
671
		configurator.setMoveDerivedUnitMediaToGallery(true);
672
		configurator.setMoveFieldObjectMediaToGallery(true);
673
		return configurator;
674
	}
675

    
676
	/**
677
	 * This method will write language properties to the config.ini located in the configuration folder
678
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
679
	 *
680
	 * @param setLanguage 0 is for german and 1 for english.
681
	 * @throws IOException
682
	 */
683
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
684
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
685
        //give warning to user if the directory has no write access
686
        if(file == null){
687
            throw new IOException();
688
        }
689
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
690
        switch(setLanguage){
691
        case 0:
692
            properties.setProperty("osgi.nl", "de");
693
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
694
            break;
695
        case 1:
696
            properties.setProperty("osgi.nl", "en");
697
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
698
            break;
699
        default:
700
            break;
701
        }
702
        save(file+"/config.ini", properties);
703
    }
704

    
705
    /**
706
     * This method loads a property from a given file and returns it.
707
     *
708
     * @param filename
709
     * @return
710
     * @throws IOException
711
     */
712
    private Properties load(String filename) throws IOException {
713
        FileInputStream in = new FileInputStream(filename);
714
        Properties prop = new Properties();
715
        prop.load(in);
716
        in.close();
717
        return prop;
718
    }
719

    
720
    /**
721
     * This method saves a property to the specified file.
722
     *
723
     * @param filename
724
     * @param properties
725
     * @throws IOException
726
     */
727
    private void save(String filename, Properties properties) throws IOException{
728
        FileOutputStream fos =  new FileOutputStream(filename);
729
        properties.store(fos, "");
730
        fos.close();
731
    }
732

    
733
    /**
734
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
735
     *
736
     * @param p2Repos
737
     */
738
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
739
        StringBuilder sb = new StringBuilder();
740
        for(MetadataRepositoryElement p2Repo : p2Repos) {
741
            sb.append(P2_REPOSITORIES_DELIM);
742
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
743
                sb.append("-");
744
            } else {
745
                sb.append(p2Repo.getName());
746
            }
747
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
748
            sb.append(p2Repo.getLocation().toString());
749
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
750
            sb.append(String.valueOf(p2Repo.isEnabled()));
751
        }
752
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
753
    }
754

    
755

    
756
    /**
757
     * Retrieves a list of previously saved P2 repositories
758
     *
759
     * @return
760
     */
761
    public static List<MetadataRepositoryElement> getP2Repositories() {
762
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
763
        String p2ReposPref =  getPreferenceStore().getString(P2_REPOSITORY_LIST);
764
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
765
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
766

    
767
            while(p2ReposPrefST.hasMoreTokens()) {
768
                String p2RepoStr = p2ReposPrefST.nextToken();
769
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
770
                if(p2ReposStrST.countTokens()==3) {
771
                    String nickname = p2ReposStrST.nextToken();
772
                    URI uri = null;
773
                    try {
774
                        uri = new URI(p2ReposStrST.nextToken());
775
                    } catch (URISyntaxException e) {
776
                        continue;
777
                    }
778
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
779
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
780
                    mre.setNickname(nickname);
781
                    mre.setEnabled(enabled);
782
                    p2Repos.add(mre);
783
                }
784
            }
785
        }
786

    
787
        return p2Repos;
788
    }
789

    
790
    /**
791
     * enables/disables nested composite. <br>
792
     *
793
     * @param ctrl - Composite to be en-/disabeld
794
     * @param enabled - boolean
795
     */
796
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
797
        if (ctrl instanceof Composite) {
798
            Composite comp = (Composite) ctrl;
799
            for (Control c : comp.getChildren()) {
800
                recursiveSetEnabled(c, enabled);
801
            }
802
        } else {
803
            ctrl.setEnabled(enabled);
804
        }
805
    }
806

    
807
    /**
808
	 * <p>
809
	 * getSortRanksNaturally
810
	 * </p>
811
	 *
812
	 * @return a boolean.
813
	 */
814
	public static boolean getSortNodesNaturally() {
815
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
816
	}
817

    
818
	/**
819
	 * <p>
820
	 * setSortRanksNaturally
821
	 * </p>
822
	 *
823
	 * @param selection
824
	 *            a boolean.
825
	 */
826
	public static void setSortNodesNaturally(boolean selection) {
827
		getPreferenceStore().setValue(SORT_NODES_NATURALLY, selection);
828
	}
829

    
830

    
831
	/**
832
	 * <p>
833
	 * getSortRanksNaturally
834
	 * </p>
835
	 *
836
	 * @return a boolean.
837
	 */
838
	public static boolean getSortNodesStrictlyAlphabetically() {
839
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
840
	}
841

    
842
	/**
843
	 * <p>
844
	 * setSortRanksNaturally
845
	 * </p>
846
	 *
847
	 * @param selection
848
	 *            a boolean.
849
	 */
850
	public static void setSortNodesStrictlyAlphabetically(boolean selection) {
851
		getPreferenceStore().setValue(SORT_NODES_ALPHABETICALLY, selection);
852
	}
853

    
854
	/**
855
	 * <p>
856
	 * setStoreNavigatorState
857
	 * </p>
858
	 *
859
	 * @param selection
860
	 *            a boolean.
861
	 */
862
	public static boolean isStoreNavigatorState() {
863
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
864

    
865
	}
866

    
867
	/**
868
	 * <p>
869
	 * setStoreNavigatorState
870
	 * </p>
871
	 *
872
	 * @param selection
873
	 *            a boolean.
874
	 */
875
	public static void setStoreNavigatorState(boolean selection) {
876
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
877

    
878
	}
879

    
880
    /**
881
     * @return
882
     */
883
    public static boolean isShowUpWidgetIsDisposedMessages() {
884
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
885
    }
886
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
887
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
888
    }
889

    
890
    /**
891
     * @return
892
     */
893
    public static boolean isShowIdInVocabularyInChecklistEditor() {
894
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
895
    }
896
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
897
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
898
    }
899

    
900
    /**
901
     * @return
902
     */
903
    public static boolean isShowRankInChecklistEditor() {
904
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
905
    }
906
    public static void setShowRankInChecklistEditor(boolean selection) {
907
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
908
    }
909

    
910
}
(18-18/24)