2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
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.
10 package eu
.etaxonomy
.taxeditor
.preference
;
13 import java
.io
.FileInputStream
;
14 import java
.io
.FileOutputStream
;
15 import java
.io
.IOException
;
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
;
23 import java
.util
.Properties
;
25 import java
.util
.StringTokenizer
;
26 import java
.util
.UUID
;
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
.Shell
;
33 import org
.eclipse
.ui
.PlatformUI
;
35 import eu
.etaxonomy
.cdm
.api
.facade
.DerivedUnitFacadeConfigurator
;
36 import eu
.etaxonomy
.cdm
.api
.service
.IFeatureTreeService
;
37 import eu
.etaxonomy
.cdm
.api
.service
.ITermService
;
38 import eu
.etaxonomy
.cdm
.api
.service
.config
.FindTaxaAndNamesConfiguratorImpl
;
39 import eu
.etaxonomy
.cdm
.api
.service
.config
.IFindTaxaAndNamesConfigurator
;
40 import eu
.etaxonomy
.cdm
.common
.CdmUtils
;
41 import eu
.etaxonomy
.cdm
.hibernate
.HibernateProxyHelper
;
42 import eu
.etaxonomy
.cdm
.model
.common
.ICdmBase
;
43 import eu
.etaxonomy
.cdm
.model
.common
.IDefinedTerm
;
44 import eu
.etaxonomy
.cdm
.model
.common
.ISimpleTerm
;
45 import eu
.etaxonomy
.cdm
.model
.common
.Language
;
46 import eu
.etaxonomy
.cdm
.model
.common
.MarkerType
;
47 import eu
.etaxonomy
.cdm
.model
.common
.TermBase
;
48 import eu
.etaxonomy
.cdm
.model
.description
.FeatureTree
;
49 import eu
.etaxonomy
.cdm
.model
.name
.NomenclaturalCode
;
50 import eu
.etaxonomy
.cdm
.strategy
.match
.DefaultMatchStrategy
;
51 import eu
.etaxonomy
.cdm
.strategy
.match
.IMatchStrategy
;
52 import eu
.etaxonomy
.cdm
.strategy
.match
.MatchException
;
53 import eu
.etaxonomy
.cdm
.strategy
.match
.MatchMode
;
54 import eu
.etaxonomy
.taxeditor
.model
.AbstractUtility
;
55 import eu
.etaxonomy
.taxeditor
.model
.MessagingUtils
;
56 import eu
.etaxonomy
.taxeditor
.model
.NomenclaturalCodeHelper
;
57 import eu
.etaxonomy
.taxeditor
.store
.CdmStore
;
58 import eu
.etaxonomy
.taxeditor
.store
.internal
.TaxeditorStorePlugin
;
59 import eu
.etaxonomy
.taxeditor
.ui
.dialog
.DefaultLanguageDialog
;
63 * PreferencesUtil class.
71 public class PreferencesUtil
implements IPreferenceKeys
{
76 public static final String PREFERRED_TERMS_CHANGE
= "preferred_terms";
78 public static final String P2_REPOSITORIES_DELIM
= ",";
79 public static final String P2_REPOSITORY_FIELDS_DELIM
= ";";
86 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
88 public static IPreferenceStore
getPreferenceStore() {
89 return TaxeditorStorePlugin
.getDefault().getPreferenceStore();
94 * setPreferredNomenclaturalCode
97 * @param preferredCode
98 * a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
101 public static void setPreferredNomenclaturalCode(
102 NomenclaturalCode preferredCode
) {
103 getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY
,
104 getPreferenceKey(preferredCode
));
109 * getPreferredNomenclaturalCode
112 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
114 public static NomenclaturalCode
getPreferredNomenclaturalCode() {
116 for (NomenclaturalCode code
: NomenclaturalCodeHelper
.getAllCodes()) {
117 String preferredCode
= getPreferenceStore().getString(
118 PREFERRED_NOMENCLATURAL_CODE_KEY
);
119 if (getPreferenceKey(code
).equals(preferredCode
)) {
126 public static String
getPreferredDefaultLangugae(){
127 String preferredLanguage
= getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR
);
128 if(StringUtils
.isNotEmpty(preferredLanguage
) && StringUtils
.isNotBlank(preferredLanguage
)){
129 return preferredLanguage
;
135 * Get the match strategy for the given class that was stored in preferences
136 * or the default strategy if it was not stored in preferences
139 * a {@link java.lang.Class} object.
140 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
142 public static IMatchStrategy
getMatchStrategy(Class clazz
) {
143 String className
= clazz
.getName();
144 if (getPreferenceStore().getBoolean(MATCH_STRATEGY_PREFIX
+ className
)) {
145 IMatchStrategy matchStrategy
= getDefaultMatchStrategy(clazz
);
147 for (String fieldName
: matchStrategy
.getMatchFieldPropertyNames()) {
148 String matchModeName
= getPreferenceStore().getString(
149 getMatchStrategyFieldName(className
, fieldName
));
150 MatchMode matchMode
= MatchMode
.valueOf(matchModeName
);
152 matchStrategy
.setMatchMode(fieldName
, matchMode
);
153 } catch (MatchException e
) {
154 MessagingUtils
.error(PreferencesUtil
.class, e
);
155 throw new RuntimeException(e
);
159 return matchStrategy
;
161 return getDefaultMatchStrategy(clazz
);
165 * Stores a matchStrategy into the preference store.
167 * @param matchStrategy
168 * a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
171 public static void setMatchStrategy(IMatchStrategy matchStrategy
) {
172 String className
= matchStrategy
.getMatchClass().getName();
173 getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX
+ className
, true);
175 Set
<String
> matchFields
= matchStrategy
.getMatchFieldPropertyNames();
177 for (String fieldName
: matchFields
) {
178 getPreferenceStore().setValue(
179 getMatchStrategyFieldName(className
, fieldName
),
180 matchStrategy
.getMatchMode(fieldName
).name());
185 * Helper method to create the preference property for a match field.
191 private static String
getMatchStrategyFieldName(String className
,
193 return MATCH_STRATEGY_PREFIX
+ className
+ "." + fieldName
;
197 * Returns the default match strategy for a given class.
200 * a {@link java.lang.Class} object.
201 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
203 public static IMatchStrategy
getDefaultMatchStrategy(Class clazz
) {
204 return DefaultMatchStrategy
.NewInstance(clazz
);
209 * getDateFormatPattern
212 * @return a {@link java.lang.String} object.
214 public static String
getDateFormatPattern() {
215 // TODO make this configurable in properties
216 String pattern
= "Y-M-d H:m";
222 * addTermToPreferredTerms
230 public static <T
extends TermBase
> void addTermToPreferredTerms(T term
) {
232 // VocabularyEnum vocabulary =
233 // VocabularyEnum.getVocabularyEnum(term.getClass());
235 // getPreferenceStore().setValue(getPreferenceKey(term),
236 // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
238 // firePreferencesChanged(term.getClass());
242 * Construct a unique key using the CdmBase object's uuid
247 private static String
getPreferenceKey(ICdmBase cdmBase
) {
248 cdmBase
= (ICdmBase
) HibernateProxyHelper
.deproxy(cdmBase
);
250 String key
= cdmBase
.getClass().getName().concat(".")
251 .concat(cdmBase
.getUuid().toString());
252 if (key
.contains("javassist")) {
253 MessagingUtils
.info("proxy");
259 * Construct a unique key using the CdmBase object's uuid
264 public static String
getPreferenceKey(ISimpleTerm simpleTerm
) {
265 simpleTerm
= (ISimpleTerm
) HibernateProxyHelper
.deproxy(simpleTerm
);
266 String key
= simpleTerm
.getClass().getName().concat(".")
267 .concat(simpleTerm
.getUuid().toString());
268 if (key
.contains("javassist")) {
269 MessagingUtils
.warn(PreferencesUtil
.class,
270 "Trying to persist a preference based on a proxy class.");
278 * Construct a unique key using the CdmBase object's uuid
283 public static String
getPreferenceKey(IDefinedTerm definedTerm
) {
284 definedTerm
= (IDefinedTerm
) HibernateProxyHelper
.deproxy(definedTerm
);
285 String key
= definedTerm
.getClass().getName().concat(".")
286 .concat(definedTerm
.getUuid().toString());
287 if (key
.contains("javassist")) {
288 MessagingUtils
.warn(PreferencesUtil
.class,
289 "Trying to persist a preference based on a proxy class.");
295 * Retrieves search preferences from the preference store
297 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
299 public static IFindTaxaAndNamesConfigurator
getSearchConfigurator() {
300 IFindTaxaAndNamesConfigurator configurator
= initializeSearchConfigurator();
302 configurator
.setDoTaxa(getPreferenceStore().getBoolean(
303 TAXON_SERVICE_CONFIGURATOR_TAXA
));
304 configurator
.setDoSynonyms(getPreferenceStore().getBoolean(
305 TAXON_SERVICE_CONFIGURATOR_SYNONYMS
));
306 configurator
.setDoNamesWithoutTaxa(getPreferenceStore().getBoolean(
307 TAXON_SERVICE_CONFIGURATOR_NAMES
));
308 configurator
.setDoTaxaByCommonNames(getPreferenceStore().getBoolean(
309 TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES
));
315 * create new preferences, setting all search options to true
318 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
321 public static IFindTaxaAndNamesConfigurator
initializeSearchConfigurator() {
322 IFindTaxaAndNamesConfigurator configurator
= new FindTaxaAndNamesConfiguratorImpl();
324 configurator
.setDoTaxa(true);
325 configurator
.setDoSynonyms(true);
326 configurator
.setDoNamesWithoutTaxa(true);
327 configurator
.setDoTaxaByCommonNames(true);
329 configurator
.setTaxonPropertyPath(Arrays
.asList("$", "titleCache",
330 "name", "name.$", "relationsFromThisTaxon.$"));
332 configurator
.setSynonymPropertyPath(Arrays
.asList("$", "titleCache",
333 "name", "name.$", "synonymRelations.relatedTo.*"));
336 // match mode is a simple like, actually all other match modes are kind
339 .setMatchMode(eu
.etaxonomy
.cdm
.persistence
.query
.MatchMode
.ANYWHERE
);
340 // we set page number and size here as this should always be unlimited
341 configurator
.setPageNumber(0);
342 // TODO currently limit results to 10000
343 configurator
.setPageSize(10000);
349 * Store search preferences
351 * @param configurator
353 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
356 public static void setSearchConfigurator(
357 IFindTaxaAndNamesConfigurator configurator
) {
358 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA
,
359 configurator
.isDoTaxa());
360 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS
,
361 configurator
.isDoSynonyms());
362 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES
,
363 configurator
.isDoNamesWithoutTaxa());
364 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES
,
365 configurator
.isDoTaxaByCommonNames());
370 * firePreferencesChanged
374 * a {@link java.lang.Class} object.
376 public static void firePreferencesChanged(Class clazz
) {
377 getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE
,
382 * Set default values for preferences
384 public static void setDefaults() {
385 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA
, true);
386 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS
,
388 getPreferenceStore().setDefault(EDIT_MAP_SERVICE_ACCES_POINT
,
389 "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
390 //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
391 getPreferenceStore().setDefault(SHOULD_CONNECT_AT_STARTUP
, false);
392 getPreferenceStore().setDefault(OPENURL_ACCESS_POINT
,
393 "http://www.biodiversitylibrary.org/openurl");
394 getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_WIDTH
, "1000");
395 getPreferenceStore().setDefault(OPENURL_IMAGE_MAX_HEIGHT
, "1000");
396 getPreferenceStore().setDefault(IPreferenceKeys
.DISTRIBUTION_AREA_PREFRENCES_ACTIVE
, false);
401 * checkNomenclaturalCode
404 public static void checkNomenclaturalCode() {
405 // First time Editor is opened, no nomenclatural code has been set
408 if (PreferencesUtil
.getPreferredNomenclaturalCode() == null) {
409 PreferencesUtil
.setPreferredNomenclaturalCode(NomenclaturalCode
.ICNAFP
);
412 StoreUtil.info("No nomencatural code set.");
414 Shell shell = StoreUtil.getShell();
416 Query user re: preferred nom. code
417 Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
420 // Short message confirming user's choice
421 NomenclaturalCode code = PreferencesUtil
422 .getPreferredNomenclaturalCode();
426 "Nomenclatural code set",
427 "The following has been set as your preferred nomenclatural code:\n\n\t"
428 + NomenclaturalCodeHelper
429 .getDescription(code)
430 + "\n\nYou can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
434 public static void checkDefaultLanguage(){
435 if(PreferencesUtil
.getPreferredDefaultLangugae() == null){
436 Shell shell
= AbstractUtility
.getShell();
437 int open
= new DefaultLanguageDialog(shell
).open();
438 if(open
== Window
.OK
){
439 PlatformUI
.getWorkbench().restart();
442 //TODO:In case of a reinstall, the config.ini will be overwritten
443 // here you create config.ini with the stored key from preferences
449 * getMapServiceAccessPoint
452 * @return a {@link java.lang.String} object.
454 public static String
getMapServiceAccessPoint() {
455 return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT
);
460 * shouldConnectAtStartUp
465 public static boolean shouldConnectAtStartUp() {
466 //FIXME : force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
467 //return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
473 * getDefaultFeatureTreeForTextualDescription
476 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
478 public static FeatureTree
getDefaultFeatureTreeForTextualDescription() {
479 String uuidString
= getPreferenceStore().getString(
480 FEATURE_TREE_DEFAULT_TEXT
);
481 return CdmUtils
.isEmpty(uuidString
) ?
null : CdmStore
.getService(
482 IFeatureTreeService
.class).load(UUID
.fromString(uuidString
));
487 * getDefaultFeatureTreeForStructuredDescription
490 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
492 public static FeatureTree
getDefaultFeatureTreeForStructuredDescription() {
493 String uuidString
= getPreferenceStore().getString(
494 FEATURE_TREE_DEFAULT_STRUCTURE
);
495 return CdmUtils
.isEmpty(uuidString
) ?
null : CdmStore
.getService(
496 IFeatureTreeService
.class).load(UUID
.fromString(uuidString
));
501 * setSortRanksHierarchichally
507 public static void setSortRanksHierarchichally(boolean selection
) {
508 getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY
, selection
);
513 * getSortRanksHierarchichally
518 public static boolean getSortRanksHierarchichally() {
519 return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY
);
522 public static boolean isMultilanguageTextEditingCapability() {
523 return getPreferenceStore().getBoolean(
524 MULTILANGUAGE_TEXT_EDITING_CAPABILITY
);
527 public static Language
getGlobalLanguage() {
530 String languageUuidString
= getPreferenceStore().getString(
531 GLOBAL_LANGUAGE_UUID
);
533 if(!CdmStore
.isActive()) {
534 MessagingUtils
.noDataSourceWarningDialog(languageUuidString
);
538 if (CdmUtils
.isBlank(languageUuidString
)) {
539 return Language
.getDefaultLanguage();
542 UUID languageUuid
= UUID
.fromString(languageUuidString
);
543 return (Language
) CdmStore
.getService(ITermService
.class).load(
547 public static void setGlobalLanguage(Language language
) {
548 if(language
!= null) {
549 getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID
,language
.getUuid().toString());
550 CdmStore
.setDefaultLanguage(language
);
558 public static Map
<MarkerType
, Boolean
> getEditMarkerTypePreferences() {
559 List
<MarkerType
> markerTypes
= CdmStore
.getTermManager()
560 .getPreferredTerms(MarkerType
.class);
562 Map
<MarkerType
, Boolean
> result
= new HashMap
<MarkerType
, Boolean
>();
564 for (MarkerType markerType
: markerTypes
) {
565 String name
= getMarkerTypeEditingPreferenceKey(markerType
);
566 Boolean value
= getPreferenceStore().getBoolean(name
);
568 result
.put(markerType
, value
);
575 * @param markerTypeEditingMap
577 public static void setEditMarkerTypePreferences(
578 Map
<MarkerType
, Boolean
> markerTypeEditingMap
) {
579 for (MarkerType markerType
: markerTypeEditingMap
.keySet()) {
580 String name
= getMarkerTypeEditingPreferenceKey(markerType
);
581 getPreferenceStore().setValue(name
,
582 markerTypeEditingMap
.get(markerType
));
587 private static String
getMarkerTypeEditingPreferenceKey(
588 MarkerType markerType
) {
589 markerType
= (MarkerType
) HibernateProxyHelper
.deproxy(markerType
);
590 return markerType
.getClass().getName() + EDIT_MARKER_TYPE_PREFIX
;
595 * setEditMarkerTypePreference
599 * a {@link org.eclipse.ui.IEditorInput} object.
601 * a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
605 public static void setEditMarkerTypePreference(MarkerType markerType
,
607 getPreferenceStore().setValue(
608 getMarkerTypeEditingPreferenceKey(markerType
), edit
);
614 public static DerivedUnitFacadeConfigurator
getDerivedUnitConfigurator() {
615 DerivedUnitFacadeConfigurator configurator
= DerivedUnitFacadeConfigurator
617 configurator
.setMoveDerivedUnitMediaToGallery(true);
618 configurator
.setMoveFieldObjectMediaToGallery(true);
623 * This method will write language properties to the config.ini located in the configuration folder
624 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
626 * @param setLanguage 0 is for german and 1 for english.
627 * @throws IOException
629 public void writePropertyToConfigFile(int setLanguage
) throws IOException
{
630 File file
= org
.eclipse
.core
.runtime
.preferences
.ConfigurationScope
.INSTANCE
.getLocation().toFile();
631 Properties properties
= load(file
.getAbsolutePath()+"/config.ini");
634 properties
.setProperty("osgi.nl", "de");
635 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "de");
638 properties
.setProperty("osgi.nl", "en");
639 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "en");
644 save(file
+"/config.ini", properties
);
648 * This method loads a property from a given file and returns it.
652 * @throws IOException
654 private Properties
load(String filename
) throws IOException
{
655 FileInputStream in
= new FileInputStream(filename
);
656 Properties prop
= new Properties();
663 * This method saves a property to the specified file.
667 * @throws IOException
669 private void save(String filename
, Properties properties
) throws IOException
{
670 FileOutputStream fos
= new FileOutputStream(filename
);
671 properties
.store(fos
, "");
676 * Saves a list of P2 Metadata Repositories as string with specified delimiters
680 public static void setP2Repositories(List
<MetadataRepositoryElement
> p2Repos
) {
681 StringBuilder sb
= new StringBuilder();
682 for(MetadataRepositoryElement p2Repo
: p2Repos
) {
683 sb
.append(P2_REPOSITORIES_DELIM
);
684 if(p2Repo
.getName() == null || p2Repo
.getName().isEmpty()) {
687 sb
.append(p2Repo
.getName());
689 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
690 sb
.append(p2Repo
.getLocation().toString());
691 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
692 sb
.append(String
.valueOf(p2Repo
.isEnabled()));
694 getPreferenceStore().setValue(P2_REPOSITORY_LIST
, sb
.toString());
699 * Retrieves a list of previously saved P2 repositories
703 public static List
<MetadataRepositoryElement
> getP2Repositories() {
704 List
<MetadataRepositoryElement
> p2Repos
= new ArrayList
<MetadataRepositoryElement
>();
705 String p2ReposPref
= getPreferenceStore().getString(P2_REPOSITORY_LIST
);
706 if(p2ReposPref
!= null && !p2ReposPref
.isEmpty()) {
707 StringTokenizer p2ReposPrefST
= new StringTokenizer(p2ReposPref
,P2_REPOSITORIES_DELIM
);
709 while(p2ReposPrefST
.hasMoreTokens()) {
710 String p2RepoStr
= p2ReposPrefST
.nextToken();
711 StringTokenizer p2ReposStrST
= new StringTokenizer(p2RepoStr
,P2_REPOSITORY_FIELDS_DELIM
);
712 if(p2ReposStrST
.countTokens()==3) {
713 String nickname
= p2ReposStrST
.nextToken();
716 uri
= new URI(p2ReposStrST
.nextToken());
717 } catch (URISyntaxException e
) {
720 boolean enabled
= Boolean
.parseBoolean(p2ReposStrST
.nextToken());
721 MetadataRepositoryElement mre
= new MetadataRepositoryElement(null, uri
, true);
722 mre
.setNickname(nickname
);
723 mre
.setEnabled(enabled
);