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");
395 getPreferenceStore().setDefault(IPreferenceKeys
.DISTRIBUTION_AREA_PREFRENCES_ACTIVE
, true);
400 * checkNomenclaturalCode
403 public static void checkNomenclaturalCode() {
404 // First time Editor is opened, no nomenclatural code has been set
407 if (PreferencesUtil
.getPreferredNomenclaturalCode() == null) {
408 PreferencesUtil
.setPreferredNomenclaturalCode(NomenclaturalCode
.ICNAFP
);
411 StoreUtil.info("No nomencatural code set.");
413 Shell shell = StoreUtil.getShell();
415 Query user re: preferred nom. code
416 Dialog dialog = new InitNomenclaturalCodePrefDialog(shell);
419 // Short message confirming user's choice
420 NomenclaturalCode code = PreferencesUtil
421 .getPreferredNomenclaturalCode();
425 "Nomenclatural code set",
426 "The following has been set as your preferred nomenclatural code:\n\n\t"
427 + NomenclaturalCodeHelper
428 .getDescription(code)
429 + "\n\nYou iour is not consistent throughout the application. For DescriptionElemts and also PolytomousKeyNode.Question and PolytomousKeyNode.Statement it shows only the languages where text is available whereas for PolytomousKeyNode.modyfingText it shows a strange list of about 10-20 (different for different nodes) most of them starting with can change the nomenclatural code at any time in the \"Preferences\" menu.");*/
433 public static void checkDefaultLanguage(){
434 if(PreferencesUtil
.getPreferredDefaultLangugae() == null){
435 Shell shell
= StoreUtil
.getShell();
436 int open
= new DefaultLanguageDialog(shell
).open();
437 if(open
== 0){//FIXME:window performed ok. Find variable for it
438 PlatformUI
.getWorkbench().restart();
441 //TODO:In case of a reinstall, the config.ini will be overwritten
442 // here you create config.ini with the stored key from preferences
448 * getMapServiceAccessPoint
451 * @return a {@link java.lang.String} object.
453 public static String
getMapServiceAccessPoint() {
454 return getPreferenceStore().getString(EDIT_MAP_SERVICE_ACCES_POINT
);
459 * shouldConnectAtStartUp
464 public static boolean shouldConnectAtStartUp() {
465 //FIXME : force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
466 //return getPreferenceStore().getBoolean(SHOULD_CONNECT_AT_STARTUP);
472 * getDefaultFeatureTreeForTextualDescription
475 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
477 public static FeatureTree
getDefaultFeatureTreeForTextualDescription() {
478 String uuidString
= getPreferenceStore().getString(
479 FEATURE_TREE_DEFAULT_TEXT
);
480 return CdmUtils
.isEmpty(uuidString
) ?
null : CdmStore
.getService(
481 IFeatureTreeService
.class).load(UUID
.fromString(uuidString
));
486 * getDefaultFeatureTreeForStructuredDescription
489 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
491 public static FeatureTree
getDefaultFeatureTreeForStructuredDescription() {
492 String uuidString
= getPreferenceStore().getString(
493 FEATURE_TREE_DEFAULT_STRUCTURE
);
494 return CdmUtils
.isEmpty(uuidString
) ?
null : CdmStore
.getService(
495 IFeatureTreeService
.class).load(UUID
.fromString(uuidString
));
500 * setSortRanksHierarchichally
506 public static void setSortRanksHierarchichally(boolean selection
) {
507 getPreferenceStore().setValue(SORT_RANKS_HIERARCHICHALLY
, selection
);
512 * getSortRanksHierarchichally
517 public static boolean getSortRanksHierarchichally() {
518 return getPreferenceStore().getBoolean(SORT_RANKS_HIERARCHICHALLY
);
521 public static boolean isMultilanguageTextEditingCapability() {
522 return getPreferenceStore().getBoolean(
523 MULTILANGUAGE_TEXT_EDITING_CAPABILITY
);
526 public static Language
getGlobalLanguage() {
529 String languageUuidString
= getPreferenceStore().getString(
530 GLOBAL_LANGUAGE_UUID
);
532 if(!CdmStore
.isActive()) {
533 MessagingUtils
.noDataSourceWarningDialog(languageUuidString
);
537 if (CdmUtils
.isBlank(languageUuidString
)) {
538 return Language
.getDefaultLanguage();
541 UUID languageUuid
= UUID
.fromString(languageUuidString
);
542 return (Language
) CdmStore
.getService(ITermService
.class).load(
546 public static void setGlobalLanguage(Language language
) {
547 if(language
!= null) {
548 getPreferenceStore().setValue(GLOBAL_LANGUAGE_UUID
,language
.getUuid().toString());
549 CdmStore
.setDefaultLanguage(language
);
557 public static Map
<MarkerType
, Boolean
> getEditMarkerTypePreferences() {
558 List
<MarkerType
> markerTypes
= CdmStore
.getTermManager()
559 .getPreferredTerms(MarkerType
.class);
561 Map
<MarkerType
, Boolean
> result
= new HashMap
<MarkerType
, Boolean
>();
563 for (MarkerType markerType
: markerTypes
) {
564 String name
= getMarkerTypeEditingPreferenceKey(markerType
);
565 Boolean value
= getPreferenceStore().getBoolean(name
);
567 result
.put(markerType
, value
);
574 * @param markerTypeEditingMap
576 public static void setEditMarkerTypePreferences(
577 Map
<MarkerType
, Boolean
> markerTypeEditingMap
) {
578 for (MarkerType markerType
: markerTypeEditingMap
.keySet()) {
579 String name
= getMarkerTypeEditingPreferenceKey(markerType
);
580 getPreferenceStore().setValue(name
,
581 markerTypeEditingMap
.get(markerType
));
586 private static String
getMarkerTypeEditingPreferenceKey(
587 MarkerType markerType
) {
588 markerType
= (MarkerType
) HibernateProxyHelper
.deproxy(markerType
);
589 return markerType
.getClass().getName() + EDIT_MARKER_TYPE_PREFIX
;
594 * setEditMarkerTypePreference
598 * a {@link org.eclipse.ui.IEditorInput} object.
600 * a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
604 public static void setEditMarkerTypePreference(MarkerType markerType
,
606 getPreferenceStore().setValue(
607 getMarkerTypeEditingPreferenceKey(markerType
), edit
);
613 public static DerivedUnitFacadeConfigurator
getDerivedUnitConfigurator() {
614 DerivedUnitFacadeConfigurator configurator
= DerivedUnitFacadeConfigurator
616 configurator
.setMoveDerivedUnitMediaToGallery(true);
617 configurator
.setMoveFieldObjectMediaToGallery(true);
622 * This method will write language properties to the config.ini located in the configuration folder
623 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
625 * @param setLanguage 0 is for german and 1 for english.
626 * @throws IOException
628 public void writePropertyToConfigFile(int setLanguage
) throws IOException
{
629 File file
= org
.eclipse
.core
.runtime
.preferences
.ConfigurationScope
.INSTANCE
.getLocation().toFile();
630 Properties properties
= load(file
.getAbsolutePath()+"/config.ini");
633 properties
.setProperty("osgi.nl", "de");
634 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "de");
637 properties
.setProperty("osgi.nl", "en");
638 PreferencesUtil
.getPreferenceStore().setValue(IPreferenceKeys
.DEFAULT_LANGUAGE_EDITOR
, "en");
643 save(file
+"/config.ini", properties
);
647 * This method loads a property from a given file and returns it.
651 * @throws IOException
653 private Properties
load(String filename
) throws IOException
{
654 FileInputStream in
= new FileInputStream(filename
);
655 Properties prop
= new Properties();
662 * This method saves a property to the specified file.
666 * @throws IOException
668 private void save(String filename
, Properties properties
) throws IOException
{
669 FileOutputStream fos
= new FileOutputStream(filename
);
670 properties
.store(fos
, "");
675 * Saves a list of P2 Metadata Repositories as string with specified delimiters
679 public static void setP2Repositories(List
<MetadataRepositoryElement
> p2Repos
) {
680 StringBuilder sb
= new StringBuilder();
681 for(MetadataRepositoryElement p2Repo
: p2Repos
) {
682 sb
.append(P2_REPOSITORIES_DELIM
);
683 if(p2Repo
.getName() == null || p2Repo
.getName().isEmpty()) {
686 sb
.append(p2Repo
.getName());
688 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
689 sb
.append(p2Repo
.getLocation().toString());
690 sb
.append(P2_REPOSITORY_FIELDS_DELIM
);
691 sb
.append(String
.valueOf(p2Repo
.isEnabled()));
693 getPreferenceStore().setValue(P2_REPOSITORY_LIST
, sb
.toString());
698 * Retrieves a list of previously saved P2 repositories
702 public static List
<MetadataRepositoryElement
> getP2Repositories() {
703 List
<MetadataRepositoryElement
> p2Repos
= new ArrayList
<MetadataRepositoryElement
>();
704 String p2ReposPref
= getPreferenceStore().getString(P2_REPOSITORY_LIST
);
705 if(p2ReposPref
!= null && !p2ReposPref
.isEmpty()) {
706 StringTokenizer p2ReposPrefST
= new StringTokenizer(p2ReposPref
,P2_REPOSITORIES_DELIM
);
708 while(p2ReposPrefST
.hasMoreTokens()) {
709 String p2RepoStr
= p2ReposPrefST
.nextToken();
710 StringTokenizer p2ReposStrST
= new StringTokenizer(p2RepoStr
,P2_REPOSITORY_FIELDS_DELIM
);
711 if(p2ReposStrST
.countTokens()==3) {
712 String nickname
= p2ReposStrST
.nextToken();
715 uri
= new URI(p2ReposStrST
.nextToken());
716 } catch (URISyntaxException e
) {
719 boolean enabled
= Boolean
.parseBoolean(p2ReposStrST
.nextToken());
720 MetadataRepositoryElement mre
= new MetadataRepositoryElement(null, uri
, true);
721 mre
.setNickname(nickname
);
722 mre
.setEnabled(enabled
);