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
.swt
.widgets
.Shell
;
32 import org
.eclipse
.ui
.PlatformUI
;
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
;
62 * PreferencesUtil class.
70 public class PreferencesUtil
implements IPreferenceKeys
{
75 public static final String PREFERRED_TERMS_CHANGE
= "preferred_terms";
77 public static final String P2_REPOSITORIES_DELIM
= ",";
78 public static final String P2_REPOSITORY_FIELDS_DELIM
= ";";
85 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
87 public static IPreferenceStore
getPreferenceStore() {
88 return TaxeditorStorePlugin
.getDefault().getPreferenceStore();
93 * setPreferredNomenclaturalCode
96 * @param preferredCode
97 * a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
100 public static void setPreferredNomenclaturalCode(
101 NomenclaturalCode preferredCode
) {
102 getPreferenceStore().setValue(PREFERRED_NOMENCLATURAL_CODE_KEY
,
103 getPreferenceKey(preferredCode
));
108 * getPreferredNomenclaturalCode
111 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
113 public static NomenclaturalCode
getPreferredNomenclaturalCode() {
115 for (NomenclaturalCode code
: NomenclaturalCodeHelper
.getAllCodes()) {
116 String preferredCode
= getPreferenceStore().getString(
117 PREFERRED_NOMENCLATURAL_CODE_KEY
);
118 if (getPreferenceKey(code
).equals(preferredCode
)) {
125 public static String
getPreferredDefaultLangugae(){
126 String preferredLanguage
= getPreferenceStore().getString(DEFAULT_LANGUAGE_EDITOR
);
127 if(StringUtils
.isNotEmpty(preferredLanguage
) && StringUtils
.isNotBlank(preferredLanguage
)){
128 return preferredLanguage
;
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
138 * a {@link java.lang.Class} object.
139 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
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
);
146 for (String fieldName
: matchStrategy
.getMatchFieldPropertyNames()) {
147 String matchModeName
= getPreferenceStore().getString(
148 getMatchStrategyFieldName(className
, fieldName
));
149 MatchMode matchMode
= MatchMode
.valueOf(matchModeName
);
151 matchStrategy
.setMatchMode(fieldName
, matchMode
);
152 } catch (MatchException e
) {
153 MessagingUtils
.error(PreferencesUtil
.class, e
);
154 throw new RuntimeException(e
);
158 return matchStrategy
;
160 return getDefaultMatchStrategy(clazz
);
164 * Stores a matchStrategy into the preference store.
166 * @param matchStrategy
167 * a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
170 public static void setMatchStrategy(IMatchStrategy matchStrategy
) {
171 String className
= matchStrategy
.getMatchClass().getName();
172 getPreferenceStore().setValue(MATCH_STRATEGY_PREFIX
+ className
, true);
174 Set
<String
> matchFields
= matchStrategy
.getMatchFieldPropertyNames();
176 for (String fieldName
: matchFields
) {
177 getPreferenceStore().setValue(
178 getMatchStrategyFieldName(className
, fieldName
),
179 matchStrategy
.getMatchMode(fieldName
).name());
184 * Helper method to create the preference property for a match field.
190 private static String
getMatchStrategyFieldName(String className
,
192 return MATCH_STRATEGY_PREFIX
+ className
+ "." + fieldName
;
196 * Returns the default match strategy for a given class.
199 * a {@link java.lang.Class} object.
200 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
202 public static IMatchStrategy
getDefaultMatchStrategy(Class clazz
) {
203 return DefaultMatchStrategy
.NewInstance(clazz
);
208 * getDateFormatPattern
211 * @return a {@link java.lang.String} object.
213 public static String
getDateFormatPattern() {
214 // TODO make this configurable in properties
215 String pattern
= "Y-M-d H:m";
221 * addTermToPreferredTerms
229 public static <T
extends TermBase
> void addTermToPreferredTerms(T term
) {
231 // VocabularyEnum vocabulary =
232 // VocabularyEnum.getVocabularyEnum(term.getClass());
234 // getPreferenceStore().setValue(getPreferenceKey(term),
235 // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
237 // firePreferencesChanged(term.getClass());
241 * Construct a unique key using the CdmBase object's uuid
246 private static String
getPreferenceKey(ICdmBase cdmBase
) {
247 cdmBase
= (ICdmBase
) HibernateProxyHelper
.deproxy(cdmBase
);
249 String key
= cdmBase
.getClass().getName().concat(".")
250 .concat(cdmBase
.getUuid().toString());
251 if (key
.contains("javassist")) {
252 MessagingUtils
.info("proxy");
258 * Construct a unique key using the CdmBase object's uuid
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.");
277 * Construct a unique key using the CdmBase object's uuid
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.");
294 * Retrieves search preferences from the preference store
296 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
298 public static IFindTaxaAndNamesConfigurator
getSearchConfigurator() {
299 IFindTaxaAndNamesConfigurator configurator
= initializeSearchConfigurator();
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
));
314 * create new preferences, setting all search options to true
317 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
320 public static IFindTaxaAndNamesConfigurator
initializeSearchConfigurator() {
321 IFindTaxaAndNamesConfigurator configurator
= new FindTaxaAndNamesConfiguratorImpl();
323 configurator
.setDoTaxa(true);
324 configurator
.setDoSynonyms(true);
325 configurator
.setDoNamesWithoutTaxa(true);
326 configurator
.setDoTaxaByCommonNames(true);
328 configurator
.setTaxonPropertyPath(Arrays
.asList("$", "titleCache",
329 "name", "name.$", "relationsFromThisTaxon.$"));
331 configurator
.setSynonymPropertyPath(Arrays
.asList("$", "titleCache",
332 "name", "name.$", "synonymRelations.relatedTo.*"));
335 // match mode is a simple like, actually all other match modes are kind
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);
348 * Store search preferences
350 * @param configurator
352 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
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());
369 * firePreferencesChanged
373 * a {@link java.lang.Class} object.
375 public static void firePreferencesChanged(Class clazz
) {
376 getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE
,
381 * Set default values for preferences
383 public static void setDefaults() {
384 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA
, true);
385 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS
,
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");
399 * checkNomenclaturalCode
402 public static void checkNomenclaturalCode() {
403 // First time Editor is opened, no nomenclatural code has been set
406 if (PreferencesUtil
.getPreferredNomenclaturalCode() == null) {
407 PreferencesUtil
.setPreferredNomenclaturalCode(NomenclaturalCode
.ICNAFP
);
410 StoreUtil.info("No nomencatural code set.");
412 Shell shell = StoreUtil.getShell();
414 Query user re: preferred nom. code
415 Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
418 // Short message confirming user's choice
419 NomenclaturalCode code = PreferencesUtil
420 .getPreferredNomenclaturalCode();
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.");*/
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();
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
447 * getMapServiceAccessPoint
450 * @return a {@link java.lang.String} object.
452 public static String
getMapServiceAccessPoint() {
453 return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT
);
458 * shouldConnectAtStartUp
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);
471 * getDefaultFeatureTreeForTextualDescription
474 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
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
));
485 * getDefaultFeatureTreeForStructuredDescription
488 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
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
));
499 * setSortRanksHierarchichally
505 public static void setSortRanksHierarchichally(boolean selection
) {
506 getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY
, selection
);
511 * getSortRanksHierarchichally
516 public static boolean getSortRanksHierarchichally() {
517 return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY
);
520 public static boolean isMultilanguageTextEditingCapability() {
521 return getPreferenceStore().getBoolean(
522 MULTILANGUAGE_TEXT_EDITING_CAPABILITY
);
525 public static Language
getGlobalLanguage() {
526 String languageUuidString
= getPreferenceStore().getString(
527 GLOBAL_LANGUAGE_UUID
);
529 if (CdmUtils
.isBlank(languageUuidString
)) {
530 return Language
.getDefaultLanguage();
533 UUID languageUuid
= UUID
.fromString(languageUuidString
);
534 return (Language
) CdmStore
.getService(ITermService
.class).load(
538 public static void setGlobalLanguage(Language language
) {
539 getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID
,
540 language
.getUuid().toString());
541 CdmStore
.setDefaultLanguage(language
);
547 public static Map
<MarkerType
, Boolean
> getEditMarkerTypePreferences() {
548 List
<MarkerType
> markerTypes
= CdmStore
.getTermManager()
549 .getPreferredTerms(MarkerType
.class);
551 Map
<MarkerType
, Boolean
> result
= new HashMap
<MarkerType
, Boolean
>();
553 for (MarkerType markerType
: markerTypes
) {
554 String name
= getMarkerTypeEditingPreferenceKey(markerType
);
555 Boolean value
= getPreferenceStore().getBoolean(name
);
557 result
.put(markerType
, value
);
564 * @param markerTypeEditingMap
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
));
576 private static String
getMarkerTypeEditingPreferenceKey(
577 MarkerType markerType
) {
578 markerType
= (MarkerType
) HibernateProxyHelper
.deproxy(markerType
);
579 return markerType
.getClass().getName() + EDIT_MARKER_TYPE_PREFIX
;
584 * setEditMarkerTypePreference
588 * a {@link org.eclipse.ui.IEditorInput} object.
590 * a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
594 public static void setEditMarkerTypePreference(MarkerType markerType
,
596 getPreferenceStore().setValue(
597 getMarkerTypeEditingPreferenceKey(markerType
), edit
);
603 public static DerivedUnitFacadeConfigurator
getDerivedUnitConfigurator() {
604 DerivedUnitFacadeConfigurator configurator
= DerivedUnitFacadeConfigurator
606 configurator
.setMoveDerivedUnitMediaToGallery(true);
607 configurator
.setMoveFieldObjectMediaToGallery(true);
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>
615 * @param setLanguage 0 is for german and 1 for english.
616 * @throws IOException
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");
623 properties
.setProperty("osgi.nl", "de");
624 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "de");
627 properties
.setProperty("osgi.nl", "en");
628 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "en");
633 save(file
+"/config.ini", properties
);
637 * This method loads a property from a given file and returns it.
641 * @throws IOException
643 private Properties
load(String filename
) throws IOException
{
644 FileInputStream in
= new FileInputStream(filename
);
645 Properties prop
= new Properties();
652 * This method saves a property to the specified file.
656 * @throws IOException
658 private void save(String filename
, Properties properties
) throws IOException
{
659 FileOutputStream fos
= new FileOutputStream(filename
);
660 properties
.store(fos
, "");
665 * Saves a list of P2 Metadata Repositories as string with specified delimiters
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 sb
.append(p2Repo
.getName());
674 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
675 sb
.append(p2Repo
.getLocation().toString());
676 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
677 sb
.append(String
.valueOf(p2Repo
.isEnabled()));
679 getPreferenceStore().setValue(P2_REPOSITORY_LIST
, sb
.toString());
684 * Retrieves a list of previously saved P2 repositories
688 public static List
<MetadataRepositoryElement
> getP2Repositories() {
689 List
<MetadataRepositoryElement
> p2Repos
= new ArrayList
<MetadataRepositoryElement
>();
690 String p2ReposPref
= getPreferenceStore().getString(P2_REPOSITORY_LIST
);
691 if(p2ReposPref
!= null && !p2ReposPref
.isEmpty()) {
692 StringTokenizer p2ReposPrefST
= new StringTokenizer(p2ReposPref
,P2_REPOSITORIES_DELIM
);
693 while(p2ReposPrefST
.hasMoreTokens()) {
694 String p2RepoStr
= p2ReposPrefST
.nextToken();
695 StringTokenizer p2ReposStrST
= new StringTokenizer(p2RepoStr
,P2_REPOSITORY_FIELDS_DELIM
);
696 String nickname
= p2ReposStrST
.nextToken();
699 uri
= new URI(p2ReposStrST
.nextToken());
700 } catch (URISyntaxException e
) {
703 boolean enabled
= Boolean
.parseBoolean(p2ReposStrST
.nextToken());
704 MetadataRepositoryElement mre
= new MetadataRepositoryElement(null, uri
, true);
705 mre
.setNickname(nickname
);
706 mre
.setEnabled(enabled
);