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 (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
	}
455

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

    
464

    
465
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
466
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
467
			/*
468

    
469
			StoreUtil.info("No nomencatural code set.");
470

    
471
			Shell shell = StoreUtil.getShell();
472

    
473
		 Query user re: preferred nom. code
474
			Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
475
			dialog.open();
476

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

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

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

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

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

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

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

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

    
579
	public static boolean isMultilanguageTextEditingCapability() {
580
		return getPreferenceStore().getBoolean(
581
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
582
	}
583

    
584
	public static Language getGlobalLanguage() {
585

    
586

    
587
		String languageUuidString = getPreferenceStore().getString(
588
				GLOBAL_LANGUAGE_UUID);
589

    
590
		if(!CdmStore.isActive()) {
591
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
592
            return null;
593
        }
594

    
595
		if (CdmUtils.isBlank(languageUuidString)) {
596
			return Language.getDefaultLanguage();
597
		}
598

    
599
		UUID languageUuid = UUID.fromString(languageUuidString);
600
		return (Language) CdmStore.getService(ITermService.class).load(
601
				languageUuid);
602
	}
603

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

    
610
	}
611

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

    
619
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
620

    
621
		for (MarkerType markerType : markerTypes) {
622
			String name = getMarkerTypeEditingPreferenceKey(markerType);
623
			Boolean value = getPreferenceStore().getBoolean(name);
624

    
625
			result.put(markerType, value);
626
		}
627

    
628
		return result;
629
	}
630

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

    
642
	}
643

    
644
	private static String getMarkerTypeEditingPreferenceKey(
645
			MarkerType markerType) {
646
		markerType = HibernateProxyHelper.deproxy(markerType);
647
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
648
	}
649

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

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

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

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

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

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

    
758

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

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

    
790
        return p2Repos;
791
    }
792

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

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

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

    
833

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

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

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

    
868
	}
869

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

    
881
	}
882

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

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

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

    
913
}
(18-18/24)