merge-update from trunk
[taxeditor.git] / eu.etaxonomy.taxeditor.store / src / main / java / eu / etaxonomy / taxeditor / preference / PreferencesUtil.java
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.util.Arrays;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Properties;
21 import java.util.Set;
22 import java.util.UUID;
23
24 import org.apache.commons.lang.StringUtils;
25 import org.eclipse.jface.preference.IPreferenceStore;
26 import org.eclipse.swt.widgets.Shell;
27 import org.eclipse.ui.PlatformUI;
28
29 import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
30 import eu.etaxonomy.cdm.api.service.IFeatureTreeService;
31 import eu.etaxonomy.cdm.api.service.ITermService;
32 import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;
33 import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;
34 import eu.etaxonomy.cdm.common.CdmUtils;
35 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
36 import eu.etaxonomy.cdm.model.common.ICdmBase;
37 import eu.etaxonomy.cdm.model.common.IDefinedTerm;
38 import eu.etaxonomy.cdm.model.common.ISimpleTerm;
39 import eu.etaxonomy.cdm.model.common.Language;
40 import eu.etaxonomy.cdm.model.common.MarkerType;
41 import eu.etaxonomy.cdm.model.common.TermBase;
42 import eu.etaxonomy.cdm.model.description.FeatureTree;
43 import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
44 import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
45 import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
46 import eu.etaxonomy.cdm.strategy.match.MatchException;
47 import eu.etaxonomy.cdm.strategy.match.MatchMode;
48 import eu.etaxonomy.taxeditor.model.MessagingUtils;
49 import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
50 import eu.etaxonomy.taxeditor.store.CdmStore;
51 import eu.etaxonomy.taxeditor.store.StoreUtil;
52 import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
53 import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
54
55 /**
56 * <p>
57 * PreferencesUtil class.
58 * </p>
59 *
60 * @author p.ciardelli
61 * @author n.hoffmann
62 * @created 05.12.2008
63 * @version 1.0
64 */
65 public class PreferencesUtil implements IPreferenceKeys {
66
67 /**
68 *
69 */
70 public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
71
72 /**
73 * <p>
74 * getPreferenceStore
75 * </p>
76 *
77 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
78 */
79 public static IPreferenceStore getPreferenceStore() {
80 return TaxeditorStorePlugin.getDefault().getPreferenceStore();
81 }
82
83 /**
84 * <p>
85 * setPreferredNomenclaturalCode
86 * </p>
87 *
88 * @param preferredCode
89 * a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
90 * object.
91 */
92 public static void setPreferredNomenclaturalCode(
93 NomenclaturalCode preferredCode) {
94 getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
95 getPreferenceKey(preferredCode));
96 }
97
98 /**
99 * <p>
100 * getPreferredNomenclaturalCode
101 * </p>
102 *
103 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
104 */
105 public static NomenclaturalCode getPreferredNomenclaturalCode() {
106
107 for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
108 String preferredCode = getPreferenceStore().getString(
109 PREFERRED_NOMENCLATURAL_CODE_KEY);
110 if (getPreferenceKey(code).equals(preferredCode)) {
111 return code;
112 }
113 }
114 return null;
115 }
116
117 public static String getPreferredDefaultLangugae(){
118 String preferredLanguage = getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR);
119 if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
120 return preferredLanguage;
121 }
122 return null;
123 }
124
125 /**
126 * Get the match strategy for the given class that was stored in preferences
127 * or the default strategy if it was not stored in preferences
128 *
129 * @param clazz
130 * a {@link java.lang.Class} object.
131 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
132 */
133 public static IMatchStrategy getMatchStrategy(Class clazz) {
134 String className = clazz.getName();
135 if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX + className)) {
136 IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
137
138 for (String fieldName : matchStrategy.getMatchFieldPropertyNames()) {
139 String matchModeName = getPreferenceStore().getString(
140 getMatchStrategyFieldName(className, fieldName));
141 MatchMode matchMode = MatchMode.valueOf(matchModeName);
142 try {
143 matchStrategy.setMatchMode(fieldName, matchMode);
144 } catch (MatchException e) {
145 MessagingUtils.error(PreferencesUtil.class, e);
146 throw new RuntimeException(e);
147 }
148 }
149
150 return matchStrategy;
151 }
152 return getDefaultMatchStrategy(clazz);
153 }
154
155 /**
156 * Stores a matchStrategy into the preference store.
157 *
158 * @param matchStrategy
159 * a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
160 * object.
161 */
162 public static void setMatchStrategy(IMatchStrategy matchStrategy) {
163 String className = matchStrategy.getMatchClass().getName();
164 getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX + className, true);
165
166 Set<String> matchFields = matchStrategy.getMatchFieldPropertyNames();
167
168 for (String fieldName : matchFields) {
169 getPreferenceStore().setValue(
170 getMatchStrategyFieldName(className, fieldName),
171 matchStrategy.getMatchMode(fieldName).name());
172 }
173 }
174
175 /**
176 * Helper method to create the preference property for a match field.
177 *
178 * @param className
179 * @param fieldName
180 * @return
181 */
182 private static String getMatchStrategyFieldName(String className,
183 String fieldName) {
184 return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
185 }
186
187 /**
188 * Returns the default match strategy for a given class.
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 getDefaultMatchStrategy(Class clazz) {
195 return DefaultMatchStrategy.NewInstance(clazz);
196 }
197
198 /**
199 * <p>
200 * getDateFormatPattern
201 * </p>
202 *
203 * @return a {@link java.lang.String} object.
204 */
205 public static String getDateFormatPattern() {
206 // TODO make this configurable in properties
207 String pattern = "Y-M-d H:m";
208 return pattern;
209 }
210
211 /**
212 * <p>
213 * addTermToPreferredTerms
214 * </p>
215 *
216 * @param term
217 * a T object.
218 * @param <T>
219 * a T object.
220 */
221 public static <T extends TermBase> void addTermToPreferredTerms(T term) {
222
223 // VocabularyEnum vocabulary =
224 // VocabularyEnum.getVocabularyEnum(term.getClass());
225 //
226 // getPreferenceStore().setValue(getPreferenceKey(term),
227 // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
228 //
229 // firePreferencesChanged(term.getClass());
230 }
231
232 /**
233 * Construct a unique key using the CdmBase object's uuid
234 *
235 * @param cdmBase
236 * @return
237 */
238 private static String getPreferenceKey(ICdmBase cdmBase) {
239 cdmBase = (ICdmBase) HibernateProxyHelper.deproxy(cdmBase);
240
241 String key = cdmBase.getClass().getName().concat(".")
242 .concat(cdmBase.getUuid().toString());
243 if (key.contains("javassist")) {
244 MessagingUtils.info("proxy");
245 }
246 return key;
247 }
248
249 /**
250 * Construct a unique key using the CdmBase object's uuid
251 *
252 * @param cdmBase
253 * @return
254 */
255 public static String getPreferenceKey(ISimpleTerm simpleTerm) {
256 simpleTerm = (ISimpleTerm) HibernateProxyHelper.deproxy(simpleTerm);
257 String key = simpleTerm.getClass().getName().concat(".")
258 .concat(simpleTerm.getUuid().toString());
259 if (key.contains("javassist")) {
260 MessagingUtils.warn(PreferencesUtil.class,
261 "Trying to persist a preference based on a proxy class.");
262 }
263 return key;
264 }
265
266
267
268 /**
269 * Construct a unique key using the CdmBase object's uuid
270 *
271 * @param cdmBase
272 * @return
273 */
274 public static String getPreferenceKey(IDefinedTerm definedTerm) {
275 definedTerm = (IDefinedTerm) HibernateProxyHelper.deproxy(definedTerm);
276 String key = definedTerm.getClass().getName().concat(".")
277 .concat(definedTerm.getUuid().toString());
278 if (key.contains("javassist")) {
279 MessagingUtils.warn(PreferencesUtil.class,
280 "Trying to persist a preference based on a proxy class.");
281 }
282 return key;
283 }
284
285 /**
286 * Retrieves search preferences from the preference store
287 *
288 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
289 */
290 public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
291 IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
292
293 configurator.setDoTaxa(getPreferenceStore().getBoolean(
294 TAXON_SERVICE_CONFIGURATOR_TAXA));
295 configurator.setDoSynonyms(getPreferenceStore().getBoolean(
296 TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
297 configurator.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
298 TAXON_SERVICE_CONFIGURATOR_NAMES));
299 configurator.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
300 TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
301
302 return configurator;
303 }
304
305 /**
306 * create new preferences, setting all search options to true
307 *
308 * @return a
309 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
310 * object.
311 */
312 public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
313 IFindTaxaAndNamesConfigurator configurator = new FindTaxaAndNamesConfiguratorImpl();
314
315 configurator.setDoTaxa(true);
316 configurator.setDoSynonyms(true);
317 configurator.setDoNamesWithoutTaxa(true);
318 configurator.setDoTaxaByCommonNames(true);
319
320 configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
321 "name", "name.$", "relationsFromThisTaxon.$"));
322
323 configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
324 "name", "name.$", "synonymRelations.relatedTo.*"));
325
326 // DEFAULT VALUES
327 // match mode is a simple like, actually all other match modes are kind
328 // of bogus
329 configurator
330 .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
331 // we set page number and size here as this should always be unlimited
332 configurator.setPageNumber(0);
333 // TODO currently limit results to 10000
334 configurator.setPageSize(10000);
335
336 return configurator;
337 }
338
339 /**
340 * Store search preferences
341 *
342 * @param configurator
343 * a
344 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
345 * object.
346 */
347 public static void setSearchConfigurator(
348 IFindTaxaAndNamesConfigurator configurator) {
349 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
350 configurator.isDoTaxa());
351 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
352 configurator.isDoSynonyms());
353 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
354 configurator.isDoNamesWithoutTaxa());
355 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
356 configurator.isDoTaxaByCommonNames());
357 }
358
359 /**
360 * <p>
361 * firePreferencesChanged
362 * </p>
363 *
364 * @param clazz
365 * a {@link java.lang.Class} object.
366 */
367 public static void firePreferencesChanged(Class clazz) {
368 getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
369 null, clazz);
370 }
371
372 /**
373 * Set default values for preferences
374 */
375 public static void setDefaults() {
376 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
377 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
378 true);
379 getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT,
380 "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
381 //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
382 getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP, false);
383 getPreferenceStore().setDefault(OPENURL_ACCESS_POINT,
384 "http://www.biodiversitylibrary.org/openurl");
385 getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH, "1000");
386 getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT, "1000");
387 }
388
389 /**
390 * <p>
391 * checkNomenclaturalCode
392 * </p>
393 */
394 public static void checkNomenclaturalCode() {
395 // First time Editor is opened, no nomenclatural code has been set
396
397
398 if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
399 PreferencesUtil.setPreferredNomenclaturalCode(NomenclaturalCode.ICNAFP);
400 /*
401
402 StoreUtil.info("No nomencatural code set.");
403
404 Shell shell = StoreUtil.getShell();
405
406 Query user re: preferred nom. code
407 Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
408 dialog.open();
409
410 // Short message confirming user's choice
411 NomenclaturalCode code = PreferencesUtil
412 .getPreferredNomenclaturalCode();
413 MessageDialog
414 .openInformation(
415 shell,
416 "Nomenclatural code set",
417 "The following has been set as your preferred nomenclatural code:\n\n\t"
418 + NomenclaturalCodeHelper
419 .getDescription(code)
420 + "\n\nYou can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
421 }
422 }
423
424 public static void checkDefaultLanguage(){
425 if(PreferencesUtil.getPreferredDefaultLangugae() == null){
426 Shell shell = StoreUtil.getShell();
427 int open = new DefaultLanguageDialog(shell).open();
428 if(open == 0){//FIXME:window performed ok. Find variable for it
429 PlatformUI.getWorkbench().restart();
430 }
431 }else{
432 //TODO:In case of a reinstall, the config.ini will be overwritten
433 // here you create config.ini with the stored key from preferences
434 }
435 }
436
437 /**
438 * <p>
439 * getMapServiceAccessPoint
440 * </p>
441 *
442 * @return a {@link java.lang.String} object.
443 */
444 public static String getMapServiceAccessPoint() {
445 return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT);
446 }
447
448 /**
449 * <p>
450 * shouldConnectAtStartUp
451 * </p>
452 *
453 * @return a boolean.
454 */
455 public static boolean shouldConnectAtStartUp() {
456 //FIXME : force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
457 //return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
458 return false;
459 }
460
461 /**
462 * <p>
463 * getDefaultFeatureTreeForTextualDescription
464 * </p>
465 *
466 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
467 */
468 public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
469 String uuidString = getPreferenceStore().getString(
470 FEATURE_TREE_DEFAULT_TEXT);
471 return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
472 IFeatureTreeService.class).load(UUID.fromString(uuidString));
473 }
474
475 /**
476 * <p>
477 * getDefaultFeatureTreeForStructuredDescription
478 * </p>
479 *
480 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
481 */
482 public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
483 String uuidString = getPreferenceStore().getString(
484 FEATURE_TREE_DEFAULT_STRUCTURE);
485 return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
486 IFeatureTreeService.class).load(UUID.fromString(uuidString));
487 }
488
489 /**
490 * <p>
491 * setSortRanksHierarchichally
492 * </p>
493 *
494 * @param selection
495 * a boolean.
496 */
497 public static void setSortRanksHierarchichally(boolean selection) {
498 getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY, selection);
499 }
500
501 /**
502 * <p>
503 * getSortRanksHierarchichally
504 * </p>
505 *
506 * @return a boolean.
507 */
508 public static boolean getSortRanksHierarchichally() {
509 return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY);
510 }
511
512 public static boolean isMultilanguageTextEditingCapability() {
513 return getPreferenceStore().getBoolean(
514 MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
515 }
516
517 public static Language getGlobalLanguage() {
518 String languageUuidString = getPreferenceStore().getString(
519 GLOBAL_LANGUAGE_UUID);
520
521 if (CdmUtils.isBlank(languageUuidString)) {
522 return Language.getDefaultLanguage();
523 }
524
525 UUID languageUuid = UUID.fromString(languageUuidString);
526 return (Language) CdmStore.getService(ITermService.class).load(
527 languageUuid);
528 }
529
530 public static void setGlobalLanguage(Language language) {
531 getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID,
532 language.getUuid().toString());
533 CdmStore.setDefaultLanguage(language);
534 }
535
536 /**
537 * @return
538 */
539 public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
540 List<MarkerType> markerTypes = CdmStore.getTermManager()
541 .getPreferredTerms(MarkerType.class);
542
543 Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
544
545 for (MarkerType markerType : markerTypes) {
546 String name = getMarkerTypeEditingPreferenceKey(markerType);
547 Boolean value = getPreferenceStore().getBoolean(name);
548
549 result.put(markerType, value);
550 }
551
552 return result;
553 }
554
555 /**
556 * @param markerTypeEditingMap
557 */
558 public static void setEditMarkerTypePreferences(
559 Map<MarkerType, Boolean> markerTypeEditingMap) {
560 for (MarkerType markerType : markerTypeEditingMap.keySet()) {
561 String name = getMarkerTypeEditingPreferenceKey(markerType);
562 getPreferenceStore().setValue(name,
563 markerTypeEditingMap.get(markerType));
564 }
565
566 }
567
568 private static String getMarkerTypeEditingPreferenceKey(
569 MarkerType markerType) {
570 markerType = (MarkerType) HibernateProxyHelper.deproxy(markerType);
571 return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
572 }
573
574 /**
575 * <p>
576 * setEditMarkerTypePreference
577 * </p>
578 *
579 * @param input
580 * a {@link org.eclipse.ui.IEditorInput} object.
581 * @param markerType
582 * a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
583 * @param edit
584 * a boolean.
585 */
586 public static void setEditMarkerTypePreference(MarkerType markerType,
587 boolean edit) {
588 getPreferenceStore().setValue(
589 getMarkerTypeEditingPreferenceKey(markerType), edit);
590 }
591
592 /**
593 * @return
594 */
595 public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
596 DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
597 .NewInstance();
598 configurator.setMoveDerivedUnitMediaToGallery(true);
599 configurator.setMoveFieldObjectMediaToGallery(true);
600 return configurator;
601 }
602
603 /**
604 * This method will write language properties to the config.ini located in the configuration folder
605 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
606 *
607 * @param setLanguage 0 is for german and 1 for english.
608 * @throws IOException
609 */
610 public void writePropertyToConfigFile(int setLanguage) throws IOException {
611 File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
612 Properties properties = load(file.getAbsolutePath()+"/config.ini");
613 switch(setLanguage){
614 case 0:
615 properties.setProperty("osgi.nl", "de");
616 PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
617 break;
618 case 1:
619 properties.setProperty("osgi.nl", "en");
620 PreferencesUtil.getPreferenceStore().setValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
621 break;
622 default:
623 break;
624 }
625 save(file+"/config.ini", properties);
626 }
627
628 /**
629 * This method loads a property from a given file and returns it.
630 *
631 * @param filename
632 * @return
633 * @throws IOException
634 */
635 private Properties load(String filename) throws IOException {
636 FileInputStream in = new FileInputStream(filename);
637 Properties prop = new Properties();
638 prop.load(in);
639 in.close();
640 return prop;
641 }
642
643 /**
644 * This method saves a property to the specified file.
645 *
646 * @param filename
647 * @param properties
648 * @throws IOException
649 */
650 private void save(String filename, Properties properties) throws IOException{
651 FileOutputStream fos = new FileOutputStream(filename);
652 properties.store(fos, "");
653 fos.close();
654 }
655
656 }