Project

General

Profile

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

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

    
174
	public static String getPreferredDefaultLangugae(){
175
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
176
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
177
	        return preferredLanguage;
178
	    }
179
	    return null;
180
	}
181

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

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

    
207
			return matchStrategy;
208
		}
209
		return getDefaultMatchStrategy(clazz);
210
	}
211

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

    
223
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
224

    
225
		for (String fieldName : matchFields) {
226
			getPreferenceStore().setValue(
227
					getMatchStrategyFieldName(className, fieldName),
228
					matchStrategy.getMatchMode(fieldName).name());
229
		}
230
	}
231

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

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

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

    
268
	/**
269
	 * <p>
270
	 * addTermToPreferredTerms
271
	 * </p>
272
	 *
273
	 * @param term
274
	 *            a T object.
275
	 * @param <T>
276
	 *            a T object.
277
	 */
278
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
279

    
280
		// VocabularyEnum vocabulary =
281
		// VocabularyEnum.getVocabularyEnum(term.getClass());
282
		//
283
		// getPreferenceStore().setValue(getPreferenceKey(term),
284
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
285
		//
286
		// firePreferencesChanged(term.getClass());
287
	}
288

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

    
298
		String key = cdmBase.getClass().getName().concat(".")
299
				.concat(cdmBase.getUuid().toString());
300
		if (key.contains("javassist")) {
301
			MessagingUtils.info("proxy");
302
		}
303
		return key;
304
	}
305

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

    
323

    
324

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

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

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

    
360
		return configurator;
361
	}
362

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

    
373
		configurator.setDoTaxa(true);
374
		configurator.setDoSynonyms(true);
375
		configurator.setDoNamesWithoutTaxa(true);
376
		configurator.setDoTaxaByCommonNames(true);
377

    
378
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
379
				"name", "name.$", "relationsFromThisTaxon.$"));
380

    
381
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
382
				"name", "name.$", "synonymRelations.relatedTo.*"));
383

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

    
394
		return configurator;
395
	}
396

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

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

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

    
449
	/**
450
	 * <p>
451
	 * checkNomenclaturalCode
452
	 * </p>
453
	 */
454
	public static void checkNomenclaturalCode() {
455
		// First time Editor is opened, no nomenclatural code has been set
456

    
457

    
458
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
459
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
460
			/*
461

    
462
			StoreUtil.info("No nomencatural code set.");
463

    
464
			Shell shell = StoreUtil.getShell();
465

    
466
		 Query user re: preferred nom. code
467
			Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
468
			dialog.open();
469

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

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

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

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

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

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

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

    
561
	/**
562
	 * <p>
563
	 * getSortRanksHierarchichally
564
	 * </p>
565
	 *
566
	 * @return a boolean.
567
	 */
568
	public static boolean getSortRanksHierarchichally() {
569
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
570
	}
571

    
572
	public static boolean isMultilanguageTextEditingCapability() {
573
		return getPreferenceStore().getBoolean(
574
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
575
	}
576

    
577
	public static Language getGlobalLanguage() {
578

    
579

    
580
		String languageUuidString = getPreferenceStore().getString(
581
				GLOBAL_LANGUAGE_UUID);
582

    
583
		if(!CdmStore.isActive()) {
584
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
585
            return null;
586
        }
587

    
588
		if (CdmUtils.isBlank(languageUuidString)) {
589
			return Language.getDefaultLanguage();
590
		}
591

    
592
		UUID languageUuid = UUID.fromString(languageUuidString);
593
		return (Language) CdmStore.getService(ITermService.class).load(
594
				languageUuid);
595
	}
596

    
597
	public static void setGlobalLanguage(Language language) {
598
	    if(language != null) {
599
	        getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
600
	        CdmStore.setDefaultLanguage(language);
601
	    }
602

    
603
	}
604

    
605
	/**
606
	 * @return
607
	 */
608
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
609
		List<MarkerType> markerTypes = CdmStore.getTermManager()
610
				.getPreferredTerms(MarkerType.class);
611

    
612
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
613

    
614
		for (MarkerType markerType : markerTypes) {
615
			String name = getMarkerTypeEditingPreferenceKey(markerType);
616
			Boolean value = getPreferenceStore().getBoolean(name);
617

    
618
			result.put(markerType, value);
619
		}
620

    
621
		return result;
622
	}
623

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

    
635
	}
636

    
637
	private static String getMarkerTypeEditingPreferenceKey(
638
			MarkerType markerType) {
639
		markerType = HibernateProxyHelper.deproxy(markerType);
640
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
641
	}
642

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

    
661
	/**
662
	 * @return
663
	 */
664
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
665
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
666
				.NewInstance();
667
		configurator.setMoveDerivedUnitMediaToGallery(true);
668
		configurator.setMoveFieldObjectMediaToGallery(true);
669
		return configurator;
670
	}
671

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

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

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

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

    
751

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

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

    
783
        return p2Repos;
784
    }
785

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

    
803
    /**
804
	 * <p>
805
	 * getSortRanksNaturally
806
	 * </p>
807
	 *
808
	 * @return a boolean.
809
	 */
810
	public static boolean getSortNodesNaturally() {
811
		return getPreferenceStore().getBoolean(SORT_NODES_NATURALLY);
812
	}
813

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

    
826

    
827
	/**
828
	 * <p>
829
	 * getSortRanksNaturally
830
	 * </p>
831
	 *
832
	 * @return a boolean.
833
	 */
834
	public static boolean getSortNodesStrictlyAlphabetically() {
835
		return getPreferenceStore().getBoolean(SORT_NODES_ALPHABETICALLY);
836
	}
837

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

    
850
	/**
851
	 * <p>
852
	 * setStoreNavigatorState
853
	 * </p>
854
	 *
855
	 * @param selection
856
	 *            a boolean.
857
	 */
858
	public static boolean isStoreNavigatorState() {
859
		return getPreferenceStore().getBoolean(RESTORE_NAVIGATOR_STATE);
860

    
861
	}
862

    
863
	/**
864
	 * <p>
865
	 * setStoreNavigatorState
866
	 * </p>
867
	 *
868
	 * @param selection
869
	 *            a boolean.
870
	 */
871
	public static void setStoreNavigatorState(boolean selection) {
872
		getPreferenceStore().setValue(RESTORE_NAVIGATOR_STATE, selection);
873

    
874
	}
875

    
876
    /**
877
     * @return
878
     */
879
    public static boolean isShowUpWidgetIsDisposedMessages() {
880
       return getPreferenceStore().getBoolean(IS_SHOW_UP_WIDGET_IS_DISPOSED);
881
    }
882
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
883
        getPreferenceStore().setValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
884
    }
885

    
886
    /**
887
     * @return
888
     */
889
    public static boolean isShowIdInVocabularyInChecklistEditor() {
890
       return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_ID_IN_VOCABULARY);
891
    }
892
    public static void setShowIdInVocabularyInChecklistEditor(boolean selection) {
893
        getPreferenceStore().setValue(CHECKLIST_ID_IN_VOCABULARY, selection);
894
    }
895

    
896
    /**
897
     * @return
898
     */
899
    public static boolean isShowRankInChecklistEditor() {
900
        return getPreferenceStore().getBoolean(IPreferenceKeys.CHECKLIST_SHOW_RANK);
901
    }
902
    public static void setShowRankInChecklistEditor(boolean selection) {
903
        getPreferenceStore().setValue(CHECKLIST_SHOW_RANK, selection);
904
    }
905

    
906
}
(18-18/24)