Project

General

Profile

Download (22.1 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.swt.widgets.Shell;
32
import org.eclipse.ui.PlatformUI;
33

    
34
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
35
import eu.etaxonomy.cdm.api.service.IFeatureTreeService;
36
import eu.etaxonomy.cdm.api.service.ITermService;
37
import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;
38
import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;
39
import eu.etaxonomy.cdm.common.CdmUtils;
40
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
41
import eu.etaxonomy.cdm.model.common.ICdmBase;
42
import eu.etaxonomy.cdm.model.common.IDefinedTerm;
43
import eu.etaxonomy.cdm.model.common.ISimpleTerm;
44
import eu.etaxonomy.cdm.model.common.Language;
45
import eu.etaxonomy.cdm.model.common.MarkerType;
46
import eu.etaxonomy.cdm.model.common.TermBase;
47
import eu.etaxonomy.cdm.model.description.FeatureTree;
48
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
49
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
50
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
51
import eu.etaxonomy.cdm.strategy.match.MatchException;
52
import eu.etaxonomy.cdm.strategy.match.MatchMode;
53
import eu.etaxonomy.taxeditor.model.MessagingUtils;
54
import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
55
import eu.etaxonomy.taxeditor.store.CdmStore;
56
import eu.etaxonomy.taxeditor.store.StoreUtil;
57
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
58
import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
59

    
60
/**
61
 * <p>
62
 * PreferencesUtil class.
63
 * </p>
64
 *
65
 * @author p.ciardelli
66
 * @author n.hoffmann
67
 * @created 05.12.2008
68
 * @version 1.0
69
 */
70
public class PreferencesUtil implements IPreferenceKeys {
71

    
72
	/**
73
	 *
74
	 */
75
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
76

    
77
	public static final String P2_REPOSITORIES_DELIM = ",";
78
	public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
79

    
80
	/**
81
	 * <p>
82
	 * getPreferenceStore
83
	 * </p>
84
	 *
85
	 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
86
	 */
87
	public static IPreferenceStore getPreferenceStore() {
88
		return TaxeditorStorePlugin.getDefault().getPreferenceStore();
89
	}
90

    
91
	/**
92
	 * <p>
93
	 * setPreferredNomenclaturalCode
94
	 * </p>
95
	 *
96
	 * @param preferredCode
97
	 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
98
	 *            object.
99
	 */
100
	public static void setPreferredNomenclaturalCode(
101
			NomenclaturalCode preferredCode) {
102
		getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
103
				getPreferenceKey(preferredCode));
104
	}
105

    
106
	/**
107
	 * <p>
108
	 * getPreferredNomenclaturalCode
109
	 * </p>
110
	 *
111
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
112
	 */
113
	public static NomenclaturalCode getPreferredNomenclaturalCode() {
114

    
115
		for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
116
			String preferredCode = getPreferenceStore().getString(
117
					PREFERRED_NOMENCLATURAL_CODE_KEY);
118
			if (getPreferenceKey(code).equals(preferredCode)) {
119
				return code;
120
			}
121
		}
122
		return null;
123
	}
124

    
125
	public static String getPreferredDefaultLangugae(){
126
	    String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
127
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
128
	        return preferredLanguage;
129
	    }
130
	    return null;
131
	}
132

    
133
	/**
134
	 * Get the match strategy for the given class that was stored in preferences
135
	 * or the default strategy if it was not stored in preferences
136
	 *
137
	 * @param clazz
138
	 *            a {@link java.lang.Class} object.
139
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
140
	 */
141
	public static IMatchStrategy getMatchStrategy(Class clazz) {
142
		String className = clazz.getName();
143
		if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
144
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
145

    
146
			for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
147
				String matchModeName = getPreferenceStore().getString(
148
						getMatchStrategyFieldName(className, fieldName));
149
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
150
				try {
151
					matchStrategy.setMatchMode(fieldName, matchMode);
152
				} catch (MatchException e) {
153
					MessagingUtils.error(PreferencesUtil.class, e);
154
					throw new RuntimeException(e);
155
				}
156
			}
157

    
158
			return matchStrategy;
159
		}
160
		return getDefaultMatchStrategy(clazz);
161
	}
162

    
163
	/**
164
	 * Stores a matchStrategy into the preference store.
165
	 *
166
	 * @param matchStrategy
167
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
168
	 *            object.
169
	 */
170
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
171
		String className = matchStrategy.getMatchClass().getName();
172
		getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
173

    
174
		Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
175

    
176
		for (String fieldName : matchFields) {
177
			getPreferenceStore().setValue(
178
					getMatchStrategyFieldName(className, fieldName),
179
					matchStrategy.getMatchMode(fieldName).name());
180
		}
181
	}
182

    
183
	/**
184
	 * Helper method to create the preference property for a match field.
185
	 *
186
	 * @param className
187
	 * @param fieldName
188
	 * @return
189
	 */
190
	private static String getMatchStrategyFieldName(String className,
191
			String fieldName) {
192
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
193
	}
194

    
195
	/**
196
	 * Returns the default match strategy for a given class.
197
	 *
198
	 * @param clazz
199
	 *            a {@link java.lang.Class} object.
200
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
201
	 */
202
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
203
		return DefaultMatchStrategy.NewInstance(clazz);
204
	}
205

    
206
	/**
207
	 * <p>
208
	 * getDateFormatPattern
209
	 * </p>
210
	 *
211
	 * @return a {@link java.lang.String} object.
212
	 */
213
	public static String getDateFormatPattern() {
214
		// TODO make this configurable in properties
215
		String pattern = "Y-M-d H:m";
216
		return pattern;
217
	}
218

    
219
	/**
220
	 * <p>
221
	 * addTermToPreferredTerms
222
	 * </p>
223
	 *
224
	 * @param term
225
	 *            a T object.
226
	 * @param <T>
227
	 *            a T object.
228
	 */
229
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
230

    
231
		// VocabularyEnum vocabulary =
232
		// VocabularyEnum.getVocabularyEnum(term.getClass());
233
		//
234
		// getPreferenceStore().setValue(getPreferenceKey(term),
235
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
236
		//
237
		// firePreferencesChanged(term.getClass());
238
	}
239

    
240
	/**
241
	 * Construct a unique key using the CdmBase object's uuid
242
	 *
243
	 * @param cdmBase
244
	 * @return
245
	 */
246
	private static String getPreferenceKey(ICdmBase cdmBase) {
247
		cdmBase = (ICdmBase) HibernateProxyHelper.deproxy(cdmBase);
248

    
249
		String key = cdmBase.getClass().getName().concat(".")
250
				.concat(cdmBase.getUuid().toString());
251
		if (key.contains("javassist")) {
252
			MessagingUtils.info("proxy");
253
		}
254
		return key;
255
	}
256

    
257
	/**
258
	 * Construct a unique key using the CdmBase object's uuid
259
	 *
260
	 * @param cdmBase
261
	 * @return
262
	 */
263
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
264
		simpleTerm = (ISimpleTerm) HibernateProxyHelper.deproxy(simpleTerm);
265
		String key = simpleTerm.getClass().getName().concat(".")
266
				.concat(simpleTerm.getUuid().toString());
267
		if (key.contains("javassist")) {
268
			MessagingUtils.warn(PreferencesUtil.class,
269
					"Trying to persist a preference based on a proxy class.");
270
		}
271
		return key;
272
	}
273

    
274

    
275

    
276
	/**
277
	 * Construct a unique key using the CdmBase object's uuid
278
	 *
279
	 * @param cdmBase
280
	 * @return
281
	 */
282
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
283
		definedTerm = (IDefinedTerm) HibernateProxyHelper.deproxy(definedTerm);
284
		String key = definedTerm.getClass().getName().concat(".")
285
				.concat(definedTerm.getUuid().toString());
286
		if (key.contains("javassist")) {
287
			MessagingUtils.warn(PreferencesUtil.class,
288
					"Trying to persist a preference based on a proxy class.");
289
		}
290
		return key;
291
	}
292

    
293
	/**
294
	 * Retrieves search preferences from the preference store
295
	 *
296
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
297
	 */
298
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
299
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
300

    
301
		configurator.setDoTaxa(getPreferenceStore().getBoolean(
302
				TAXON_SERVICE_CONFIGURATOR_TAXA));
303
		configurator.setDoSynonyms(getPreferenceStore().getBoolean(
304
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
305
		configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
306
				TAXON_SERVICE_CONFIGURATOR_NAMES));
307
		configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
308
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
309

    
310
		return configurator;
311
	}
312

    
313
	/**
314
	 * create new preferences, setting all search options to true
315
	 *
316
	 * @return a
317
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
318
	 *         object.
319
	 */
320
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
321
		IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
322

    
323
		configurator.setDoTaxa(true);
324
		configurator.setDoSynonyms(true);
325
		configurator.setDoNamesWithoutTaxa(true);
326
		configurator.setDoTaxaByCommonNames(true);
327

    
328
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
329
				"name", "name.$", "relationsFromThisTaxon.$"));
330

    
331
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
332
				"name", "name.$", "synonymRelations.relatedTo.*"));
333

    
334
		// DEFAULT VALUES
335
		// match mode is a simple like, actually all other match modes are kind
336
		// of bogus
337
		configurator
338
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
339
		// we set page number and size here as this should always be unlimited
340
		configurator.setPageNumber(0);
341
		// TODO currently limit results to 10000
342
		configurator.setPageSize(10000);
343

    
344
		return configurator;
345
	}
346

    
347
	/**
348
	 * Store search preferences
349
	 *
350
	 * @param configurator
351
	 *            a
352
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
353
	 *            object.
354
	 */
355
	public static void setSearchConfigurator(
356
			IFindTaxaAndNamesConfigurator configurator) {
357
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
358
				configurator.isDoTaxa());
359
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
360
				configurator.isDoSynonyms());
361
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
362
				configurator.isDoNamesWithoutTaxa());
363
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
364
				configurator.isDoTaxaByCommonNames());
365
	}
366

    
367
	/**
368
	 * <p>
369
	 * firePreferencesChanged
370
	 * </p>
371
	 *
372
	 * @param clazz
373
	 *            a {@link java.lang.Class} object.
374
	 */
375
	public static void firePreferencesChanged(Class clazz) {
376
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
377
				null, clazz);
378
	}
379

    
380
	/**
381
	 * Set default values for preferences
382
	 */
383
	public static void setDefaults() {
384
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
385
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
386
				true);
387
		getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
388
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
389
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
390
		getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
391
		getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
392
				"http://www.biodiversitylibrary.org/openurl");
393
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
394
		getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
395
	}
396

    
397
	/**
398
	 * <p>
399
	 * checkNomenclaturalCode
400
	 * </p>
401
	 */
402
	public static void checkNomenclaturalCode() {
403
		// First time Editor is opened, no nomenclatural code has been set
404

    
405

    
406
		if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
407
			PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
408
			/*
409

    
410
			StoreUtil.info("No nomencatural code set.");
411

    
412
			Shell shell = StoreUtil.getShell();
413

    
414
		 Query user re: preferred nom. code
415
			Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
416
			dialog.open();
417

    
418
			// Short message confirming user's choice
419
			NomenclaturalCode code = PreferencesUtil
420
					.getPreferredNomenclaturalCode();
421
			MessageDialog
422
					.openInformation(
423
							shell,
424
							"Nomenclatural code set",
425
							"The following has been set as your preferred nomenclatural code:\n\n\t"
426
									+ NomenclaturalCodeHelper
427
											.getDescription(code)
428
									+ "\n\nYou can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
429
		}
430
	}
431

    
432
	public static void checkDefaultLanguage(){
433
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
434
	       Shell shell = StoreUtil.getShell();
435
	       int open = new DefaultLanguageDialog(shell).open();
436
	       if(open == 0){//FIXME:window performed ok. Find variable for it
437
	           PlatformUI.getWorkbench().restart();
438
	       }
439
	    }else{
440
	        //TODO:In case of a reinstall, the config.ini will be overwritten
441
	        //     here you create config.ini with the stored key from preferences
442
	    }
443
	}
444

    
445
	/**
446
	 * <p>
447
	 * getMapServiceAccessPoint
448
	 * </p>
449
	 *
450
	 * @return a {@link java.lang.String} object.
451
	 */
452
	public static String getMapServiceAccessPoint() {
453
		return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
454
	}
455

    
456
	/**
457
	 * <p>
458
	 * shouldConnectAtStartUp
459
	 * </p>
460
	 *
461
	 * @return a boolean.
462
	 */
463
	public static boolean shouldConnectAtStartUp() {
464
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
465
		//return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
466
		return false;
467
	}
468

    
469
	/**
470
	 * <p>
471
	 * getDefaultFeatureTreeForTextualDescription
472
	 * </p>
473
	 *
474
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
475
	 */
476
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
477
		String uuidString = getPreferenceStore().getString(
478
				FEATURE_TREE_DEFAULT_TEXT);
479
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
480
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
481
	}
482

    
483
	/**
484
	 * <p>
485
	 * getDefaultFeatureTreeForStructuredDescription
486
	 * </p>
487
	 *
488
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
489
	 */
490
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
491
		String uuidString = getPreferenceStore().getString(
492
				FEATURE_TREE_DEFAULT_STRUCTURE);
493
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
494
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
495
	}
496

    
497
	/**
498
	 * <p>
499
	 * setSortRanksHierarchichally
500
	 * </p>
501
	 *
502
	 * @param selection
503
	 *            a boolean.
504
	 */
505
	public static void setSortRanksHierarchichally(boolean selection) {
506
		getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
507
	}
508

    
509
	/**
510
	 * <p>
511
	 * getSortRanksHierarchichally
512
	 * </p>
513
	 *
514
	 * @return a boolean.
515
	 */
516
	public static boolean getSortRanksHierarchichally() {
517
		return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
518
	}
519

    
520
	public static boolean isMultilanguageTextEditingCapability() {
521
		return getPreferenceStore().getBoolean(
522
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
523
	}
524

    
525
	public static Language getGlobalLanguage() {
526
		String languageUuidString = getPreferenceStore().getString(
527
				GLOBAL_LANGUAGE_UUID);
528

    
529
		if (CdmUtils.isBlank(languageUuidString)) {
530
			return Language.getDefaultLanguage();
531
		}
532

    
533
		UUID languageUuid = UUID.fromString(languageUuidString);
534
		return (Language) CdmStore.getService(ITermService.class).load(
535
				languageUuid);
536
	}
537

    
538
	public static void setGlobalLanguage(Language language) {
539
		getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,
540
				language.getUuid().toString());
541
		CdmStore.setDefaultLanguage(language);
542
	}
543

    
544
	/**
545
	 * @return
546
	 */
547
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
548
		List<MarkerType> markerTypes = CdmStore.getTermManager()
549
				.getPreferredTerms(MarkerType.class);
550

    
551
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
552

    
553
		for (MarkerType markerType : markerTypes) {
554
			String name = getMarkerTypeEditingPreferenceKey(markerType);
555
			Boolean value = getPreferenceStore().getBoolean(name);
556

    
557
			result.put(markerType, value);
558
		}
559

    
560
		return result;
561
	}
562

    
563
	/**
564
	 * @param markerTypeEditingMap
565
	 */
566
	public static void setEditMarkerTypePreferences(
567
			Map<MarkerType, Boolean> markerTypeEditingMap) {
568
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
569
			String name = getMarkerTypeEditingPreferenceKey(markerType);
570
			getPreferenceStore().setValue(name,
571
					markerTypeEditingMap.get(markerType));
572
		}
573

    
574
	}
575

    
576
	private static String getMarkerTypeEditingPreferenceKey(
577
			MarkerType markerType) {
578
		markerType = (MarkerType) HibernateProxyHelper.deproxy(markerType);
579
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
580
	}
581

    
582
	/**
583
	 * <p>
584
	 * setEditMarkerTypePreference
585
	 * </p>
586
	 *
587
	 * @param input
588
	 *            a {@link org.eclipse.ui.IEditorInput} object.
589
	 * @param markerType
590
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
591
	 * @param edit
592
	 *            a boolean.
593
	 */
594
	public static void setEditMarkerTypePreference(MarkerType markerType,
595
			boolean edit) {
596
		getPreferenceStore().setValue(
597
				getMarkerTypeEditingPreferenceKey(markerType), edit);
598
	}
599

    
600
	/**
601
	 * @return
602
	 */
603
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
604
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
605
				.NewInstance();
606
		configurator.setMoveDerivedUnitMediaToGallery(true);
607
		configurator.setMoveFieldObjectMediaToGallery(true);
608
		return configurator;
609
	}
610

    
611
	/**
612
	 * This method will write language properties to the config.ini located in the configuration folder
613
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
614
	 *
615
	 * @param setLanguage 0 is for german and 1 for english.
616
	 * @throws IOException
617
	 */
618
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
619
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
620
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
621
        switch(setLanguage){
622
        case 0:
623
            properties.setProperty("osgi.nl", "de");
624
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
625
            break;
626
        case 1:
627
            properties.setProperty("osgi.nl", "en");
628
            PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
629
            break;
630
        default:
631
            break;
632
        }
633
        save(file+"/config.ini", properties);
634
    }
635

    
636
    /**
637
     * This method loads a property from a given file and returns it.
638
     *
639
     * @param filename
640
     * @return
641
     * @throws IOException
642
     */
643
    private Properties load(String filename) throws IOException {
644
        FileInputStream in = new FileInputStream(filename);
645
        Properties prop = new Properties();
646
        prop.load(in);
647
        in.close();
648
        return prop;
649
    }
650

    
651
    /**
652
     * This method saves a property to the specified file.
653
     *
654
     * @param filename
655
     * @param properties
656
     * @throws IOException
657
     */
658
    private void save(String filename, Properties properties) throws IOException{
659
        FileOutputStream fos =  new FileOutputStream(filename);
660
        properties.store(fos, "");
661
        fos.close();
662
    }
663

    
664
    /**
665
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
666
     *
667
     * @param p2Repos
668
     */
669
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
670
        StringBuilder sb = new StringBuilder();
671
        for(MetadataRepositoryElement p2Repo : p2Repos) {
672
            sb.append(P2_REPOSITORIES_DELIM);
673
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
674
                sb.append("-");
675
            } else {
676
                sb.append(p2Repo.getName());
677
            }
678
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
679
            sb.append(p2Repo.getLocation().toString());
680
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
681
            sb.append(String.valueOf(p2Repo.isEnabled()));
682
        }
683
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
684
    }
685

    
686

    
687
    /**
688
     * Retrieves a list of previously saved P2 repositories
689
     *
690
     * @return
691
     */
692
    public static List<MetadataRepositoryElement> getP2Repositories() {
693
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
694
        String p2ReposPref =  getPreferenceStore().getString(P2_REPOSITORY_LIST);
695
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
696
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
697

    
698
            while(p2ReposPrefST.hasMoreTokens()) {
699
                String p2RepoStr = p2ReposPrefST.nextToken();
700
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
701
                if(p2ReposStrST.countTokens()==3) {
702
                    String nickname = p2ReposStrST.nextToken();
703
                    URI uri = null;
704
                    try {
705
                        uri = new URI(p2ReposStrST.nextToken());
706
                    } catch (URISyntaxException e) {
707
                        continue;
708
                    }
709
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
710
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
711
                    mre.setNickname(nickname);
712
                    mre.setEnabled(enabled);
713
                    p2Repos.add(mre);
714
                }
715
            }
716
        }
717

    
718
        return p2Repos;
719
    }
720
}
(15-15/21)