ref #9359 upgrade TaxEditor to log4j2
[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.lang.reflect.Field;
17 import java.net.URISyntaxException;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Properties;
26 import java.util.Set;
27 import java.util.StringTokenizer;
28 import java.util.UUID;
29
30 import org.apache.commons.lang3.StringUtils;
31 import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;
32 import org.eclipse.core.runtime.preferences.ConfigurationScope;
33 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
34 import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement;
35 import org.eclipse.jface.preference.IPreferenceStore;
36 import org.eclipse.jface.window.Window;
37 import org.eclipse.swt.widgets.Composite;
38 import org.eclipse.swt.widgets.Control;
39 import org.eclipse.swt.widgets.Shell;
40 import org.eclipse.ui.PlatformUI;
41 import org.osgi.service.prefs.BackingStoreException;
42 import org.osgi.service.prefs.Preferences;
43
44 import eu.etaxonomy.cdm.api.application.ICdmRepository;
45 import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
46 import eu.etaxonomy.cdm.api.service.ITermService;
47 import eu.etaxonomy.cdm.api.service.ITermTreeService;
48 import eu.etaxonomy.cdm.api.service.IVocabularyService;
49 import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;
50 import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;
51 import eu.etaxonomy.cdm.api.service.config.SecundumForSubtreeConfigurator;
52 import eu.etaxonomy.cdm.common.CdmUtils;
53 import eu.etaxonomy.cdm.common.URI;
54 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
55 import eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator;
56 import eu.etaxonomy.cdm.model.common.ICdmBase;
57 import eu.etaxonomy.cdm.model.common.Language;
58 import eu.etaxonomy.cdm.model.common.MarkerType;
59 import eu.etaxonomy.cdm.model.description.Feature;
60 import eu.etaxonomy.cdm.model.metadata.CdmPreference;
61 import eu.etaxonomy.cdm.model.metadata.CdmPreference.PrefKey;
62 import eu.etaxonomy.cdm.model.metadata.EnabledComputedDescription;
63 import eu.etaxonomy.cdm.model.metadata.IPreferencePredicate;
64 import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
65 import eu.etaxonomy.cdm.model.metadata.PreferenceSubject;
66 import eu.etaxonomy.cdm.model.metadata.SecReferenceHandlingEnum;
67 import eu.etaxonomy.cdm.model.metadata.SecReferenceHandlingSwapEnum;
68 import eu.etaxonomy.cdm.model.metadata.TermDisplayEnum;
69 import eu.etaxonomy.cdm.model.metadata.TermOrder;
70 import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
71 import eu.etaxonomy.cdm.model.term.IDefinedTerm;
72 import eu.etaxonomy.cdm.model.term.ISimpleTerm;
73 import eu.etaxonomy.cdm.model.term.TermBase;
74 import eu.etaxonomy.cdm.model.term.TermTree;
75 import eu.etaxonomy.cdm.model.term.TermType;
76 import eu.etaxonomy.cdm.model.term.TermVocabulary;
77 import eu.etaxonomy.cdm.model.term.VocabularyEnum;
78 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
79 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDtoByNameComparator;
80 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDtoByRankAndNameComparator;
81 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDtoNaturalComparator;
82 import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
83 import eu.etaxonomy.cdm.strategy.match.FieldMatcher;
84 import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
85 import eu.etaxonomy.cdm.strategy.match.MatchException;
86 import eu.etaxonomy.cdm.strategy.match.MatchMode;
87 import eu.etaxonomy.taxeditor.editor.definedterm.input.TermEditorInput;
88 import eu.etaxonomy.taxeditor.model.AbstractUtility;
89 import eu.etaxonomy.taxeditor.model.MessagingUtils;
90 import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
91 import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
92 import eu.etaxonomy.taxeditor.store.CdmStore;
93 import eu.etaxonomy.taxeditor.store.TermStore;
94 import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
95 import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
96
97 /**
98 * <p>
99 * PreferencesUtil class.
100 * </p>
101 *
102 * @author p.ciardelli
103 * @author n.hoffmann
104 * @created 05.12.2008
105 */
106 public class PreferencesUtil implements IPreferenceKeys {
107 private final static String EDITOR_PREFERENCES_NODE = "eu.etaxonomy.taxeditor";
108
109 public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
110 public static final String UPDATE_NAVIGATOR = "update_navigator";
111 public static final String P2_REPOSITORIES_DELIM = ",";
112 public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
113 public static final String SUBJECT_DELIM = "/";
114
115 private static TermTree<Feature> preferredNameFeatureTree;
116
117 private static TermTree<Feature> preferredTaxonFeatureTree;
118
119
120
121 private final static Logger logger = LogManager.getLogger(PreferencesUtil.class);
122
123 public static IPreferenceStore getPreferenceStore() {
124 return TaxeditorStorePlugin.getDefault().getPreferenceStore();
125 }
126
127 public static String[] extractSubjectParts(String subject){
128 String[] result = subject.split("/");
129 return result;
130 }
131
132 public static IEclipsePreferences getEditorPreferences(){
133 return ConfigurationScope.INSTANCE.getNode(EDITOR_PREFERENCES_NODE);
134 }
135
136 public static String getPreferenceValue(PrefKey prefKey){
137 try {
138 //check if there exist a node for the predicate
139 if(getEditorPreferences().nodeExists(prefKey.getPredicate())){
140 Preferences predicateNode = getEditorPreferences().node(prefKey.getPredicate());
141 String[] splittedSubject = extractSubjectParts(prefKey.getSubject());
142 //check if the predicate node contains a node for the subject, this should be the last part
143 String value = predicateNode.get(splittedSubject[splittedSubject.length-1], PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue() != null? PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue().toString(): "");
144 int index = splittedSubject.length -2;
145 while (value != null && index >= 0){
146 value = predicateNode.get(splittedSubject[index], prefKey.getPredicate());
147 index--;
148 }
149 return value;
150 }
151
152 } catch (BackingStoreException e) {
153 // TODO Auto-generated catch block
154 e.printStackTrace();
155 }
156 return null;
157 }
158
159 public static List<CdmPreference> getPreference(PreferencePredicate prefPredicate){
160 try {
161 List<CdmPreference> prefs = new ArrayList<>();
162 CdmPreference pref;
163 PreferenceSubject subject;
164 if(getEditorPreferences().nodeExists(prefPredicate.getKey())){
165 Preferences predicateNode = getEditorPreferences().node(prefPredicate.getKey());
166 for (String childName: predicateNode.childrenNames()){
167 Preferences child = predicateNode.node(childName);
168 String subjectString = "";
169 subjectString = createSubjectStringForChildNodes(childName, child);
170 String value = child.get(subjectString, "");
171 subject = PreferenceSubject.NewInstance(subjectString);
172 pref = CdmPreference.NewInstance(subject, prefPredicate, value);
173 prefs.add(pref);
174 }
175 }
176 } catch (BackingStoreException e) {
177 // TODO Auto-generated catch block
178 e.printStackTrace();
179 }
180 return null;
181 }
182
183 private static String createSubjectStringForChildNodes(String subject, Preferences parent) {
184 try {
185 for (String childName: parent.childrenNames()){
186 subject = childName+SUBJECT_DELIM+subject;
187 Preferences child = parent.node(childName);
188 createSubjectStringForChildNodes(subject, child);
189 }
190 } catch (BackingStoreException e) {
191 // TODO Auto-generated catch block
192 e.printStackTrace();
193 }
194 return subject;
195
196 }
197
198 private static String prefKey(String name) {
199 return name + "_"+ ((ICdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
200 }
201
202 public static String prefOverrideKey(String name) {
203 return name + "_OVERRIDE_";
204 }
205
206 public static void setStringValue(String name, String value) {
207 if (value != null){
208 getPreferenceStore().setValue(prefKey(name), value);
209 }else{
210 getPreferenceStore().setToDefault(prefKey(name));
211 }
212 }
213
214 public static void setIntValue(String name, int value) {
215 getPreferenceStore().setValue(prefKey(name), value);
216 }
217
218 public static void setBooleanValue(String name, boolean value) {
219 getPreferenceStore().setValue(prefKey(name), value);
220 }
221
222 public static void setDoubleValue(String name, double value) {
223 getPreferenceStore().setValue(prefKey(name), value);
224 }
225
226 public static void setFloatValue(String name, float value) {
227 getPreferenceStore().setValue(prefKey(name), value);
228 }
229
230 public static void setLongValue(String name, long value) {
231 getPreferenceStore().setValue(prefKey(name), value);
232 }
233
234 public static String getStringValue(String name, boolean local) {
235
236 CdmPreference pref = getDBPreferenceValue(name);
237
238 boolean override = getOverrideForPreference(name);
239
240 if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
241 //local preference
242 String dbSpecific = prefKey(name);
243 if (getPreferenceStore().contains(dbSpecific)){
244 return getPreferenceStore().getString(dbSpecific);
245 }
246 }else if (pref != null){
247 //db preference
248 if (pref.getValue() == null){
249 Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
250 if (result instanceof String){
251 return (String)result;
252 }else{
253 return result != null?result.toString(): null;
254 }
255 }
256 return pref.getValue();
257 }
258 //no override but default value
259 IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
260 if (pred != null){
261 if (pred.getDefaultValue() instanceof String){
262 return (String)pred.getDefaultValue();
263 }else if (pred.getDefaultValue() != null){
264 return pred.getDefaultValue().toString();
265 }
266 }
267 return null;
268 }
269
270 public static String getStringValue(String name){
271 return getStringValue(name, false);
272 }
273
274 private static CdmPreference getDBPreferenceValue(String name) {
275 CdmPreferenceCache cache = CdmPreferenceCache.instance();
276 CdmPreference pref = null;
277 pref = cache.get(name);
278
279 return pref;
280 }
281
282 public static int getIntValue(String name, boolean local) {
283 CdmPreference pref= getDBPreferenceValue(name);
284 String prefValue = null;
285 if (pref != null){
286 prefValue = pref.getValue();
287 }
288 Integer result = null;
289 try{
290 result = Integer.parseInt(prefValue);
291 }catch(NumberFormatException e){
292 logger.debug("Preference value of " + name + " is not an integer");
293 }
294
295 boolean override = getOverrideForPreference(name);
296 if (local || (pref == null && override) || (pref != null && pref.isAllowOverride() && override)){
297 String dbSpecific = prefKey(name);
298 if (getPreferenceStore().contains(dbSpecific)){
299 result = getPreferenceStore().getInt(dbSpecific);
300 }
301 }
302 if (result == null){
303 IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
304 if (pred != null){
305 if (pred.getDefaultValue() instanceof Integer){
306 result = (Integer)pred.getDefaultValue();
307 }else if (pred.getDefaultValue() != null){
308 try{
309 result = Integer.valueOf(pred.getDefaultValue().toString());
310 }catch(NumberFormatException e){
311 logger.debug("Preference value of " + name + " is not a number");
312 result = 0;
313 }
314 }
315 }
316 //if no default value available
317 if (result == null){
318 result = 0;
319 }
320 }
321 return result;
322 }
323
324 public static boolean getBooleanValue(String name) {
325 Boolean result = getBooleanValue(name, false);
326 if (result == null){
327 return false;
328 }else{
329 return result;
330 }
331 }
332
333 public static Boolean getBooleanValue(String name, boolean local) {
334 if (CdmStore.isActive()){
335 CdmPreference pref = getDBPreferenceValue(name);
336 String overrideKey = createPreferenceString(createOverridePreferenceString(name));
337 boolean override = getPreferenceStore().getBoolean(overrideKey);
338 if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
339 //local preference
340 String dbSpecific = prefKey(name);
341 return getPreferenceStore().getBoolean(dbSpecific);
342
343 }else if (pref != null){
344 //db preference is available and override == false
345 if (pref.getValue() == null){
346 Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
347 if (result instanceof Boolean){
348 return (Boolean)result;
349 }else{
350 return Boolean.valueOf(result.toString());
351 }
352 }
353 return Boolean.valueOf(pref.getValue());
354 }
355 //no override but default value
356 IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
357 if (pred != null){
358 if (pred.getDefaultValue() instanceof Boolean){
359 return (Boolean)pred.getDefaultValue();
360 }else if (pred.getDefaultValue() != null){
361 return Boolean.valueOf(pred.getDefaultValue().toString());
362 }
363 }
364 return false;
365 }else{
366 // no connection to db, use local preference
367 return getPreferenceStore().getBoolean(name);
368 }
369 }
370
371 public static float getFloatValue(String name, boolean local) {
372 CdmPreference pref = getDBPreferenceValue(name);
373 String prefValue = null;
374 if (pref != null){
375 prefValue = pref.getValue();
376 }
377 Float result = null;
378 try{
379 if (prefValue != null){
380 result = Float.parseFloat(prefValue);
381 }
382 }catch(NumberFormatException e){
383 logger.debug("Preference value of " + name + " is not a float");
384 }
385
386 boolean override = getOverrideForPreference(name);
387
388 if (local || pref == null || (pref.isAllowOverride() && override)){
389 String dbSpecific = prefKey(name);
390 if (getPreferenceStore().contains(dbSpecific)){
391 result = getPreferenceStore().getFloat(dbSpecific);
392 }else{
393 IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
394 if (pred != null){
395 if (pred.getDefaultValue() instanceof Float){
396 return (float)pred.getDefaultValue();
397 }else if (pred.getDefaultValue() != null){
398 return Float.valueOf(pred.getDefaultValue().toString());
399 }
400 }
401 return 0;
402 }
403 }
404 return result;
405 }
406
407 public static CdmPreference setPreferredNomenclaturalCode(
408 String preferenceValue, boolean local) {
409 if (local){
410 setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
411 preferenceValue);
412 }
413 else{
414 ICdmRepository controller;
415 controller = CdmStore.getCurrentApplicationConfiguration();
416 if (controller == null){
417 return null;
418 }
419 PrefKey key = null;
420 try{
421 key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
422 }catch (Exception e){
423 System.out.println(e.getStackTrace());
424 }
425 CdmPreference preference = null;
426
427 if (preferenceValue == null){
428 preference = controller.getPreferenceService().find(key);
429 if (preference == null){
430 return null;
431 } else{
432 setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
433 preference.getValue());
434
435 return preference;
436 }
437 } else{
438 preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
439 controller.getPreferenceService().set(preference);
440
441 }
442 }
443 return null;
444 }
445
446 public static void setPreferredNomenclaturalCode(
447 CdmPreference preference) {
448
449 ICdmRepository controller;
450 controller = CdmStore.getCurrentApplicationConfiguration();
451 if (controller == null){
452 return;
453 }
454
455 if (preference == null){
456 PrefKey key = null;
457 try{
458 key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
459 }catch (Exception e){
460 System.out.println(e.getStackTrace());
461 }
462 controller.getPreferenceService().remove(key);
463 }else{
464 controller.getPreferenceService().set(preference);
465 }
466 }
467
468 public static NomenclaturalCode getPreferredNomenclaturalCode() {
469
470 String nomString = getStringValue(PreferencePredicate.NomenclaturalCode.getKey());
471 return getPreferredNomenclaturalCode(nomString);
472 }
473
474 public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
475
476 for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
477 if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
478 return code;
479 }
480 }
481 return null;
482 }
483
484 public static boolean isShowTaxonAssociations(){
485 boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
486 return result;
487 }
488
489 public static boolean isShowLifeForm(){
490 boolean result = getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
491 return result;
492 }
493
494 public static boolean isDeterminationOnlyForFieldUnits(){
495 boolean result = getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
496 return result;
497 }
498
499 public static boolean isCollectingAreaInGeneralSection(){
500 boolean result = getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
501 return result;
502 }
503
504 public static CdmPreference getPreferenceFromDB(IPreferencePredicate<?> predicate){
505 ICdmRepository controller;
506 CdmPreference pref = null;
507
508 try{
509 if(CdmStore.isActive()){
510 controller = CdmStore.getCurrentApplicationConfiguration();
511 PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
512 pref = controller.getPreferenceService().find(key);
513 }
514 }catch(Exception e){
515 e.printStackTrace();
516 }
517
518 return pref;
519 }
520
521 public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate<?> predicate){
522 ICdmRepository controller;
523 List<CdmPreference> prefs = null;
524
525 try{
526 if(CdmStore.isActive()){
527 controller = CdmStore.getCurrentApplicationConfiguration();
528 PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
529 prefs = controller.getPreferenceService().list(predicate);
530 }
531 }catch(Exception e){
532 e.printStackTrace();
533 }
534
535 return prefs;
536
537 }
538
539 public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
540 ICdmRepository controller;
541 try{
542 if(CdmStore.isActive()){
543 controller = CdmStore.getCurrentApplicationConfiguration();
544
545 if (setDefault){
546 controller.getPreferenceService().remove(preference.getKey());
547 }else{
548 controller.getPreferenceService().set(preference);
549 }
550 }
551 }catch(Exception e){
552 e.printStackTrace();
553 }
554 }
555
556 public static CdmPreference getPreferenceFromDB(PrefKey key){
557 ICdmRepository controller;
558 CdmPreference pref = null;
559
560 try{
561 if(CdmStore.isActive()){
562 controller = CdmStore.getCurrentApplicationConfiguration();
563 pref = controller.getPreferenceService().find(key);
564 }
565 }catch(Exception e){
566 e.printStackTrace();
567 }
568
569 return pref;
570
571 }
572
573 public static void setPreferenceToDB(CdmPreference preference){
574 ICdmRepository controller;
575 try{
576 if(CdmStore.isActive()){
577 controller = CdmStore.getCurrentApplicationConfiguration();
578 if (preference.getValue() == null && preference.isAllowOverride()){
579 controller.getPreferenceService().remove(preference.getKey());
580 }else{
581 controller.getPreferenceService().set(preference);
582 }
583 CdmPreferenceCache.instance().put(preference);
584 }
585 }catch(Exception e){
586 e.printStackTrace();
587 }
588 }
589
590 public static String getPreferredDefaultLangugae(){
591 String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR, true);
592 if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
593 return preferredLanguage;
594 }
595 return null;
596 }
597
598 public static boolean isShowMediaPreview(){
599 boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW, true);
600 return isShowMediaPreview;
601 }
602
603 /**
604 * Get the match strategy for the given class that was stored in preferences
605 * or the default strategy if it was not stored in preferences
606 *
607 * @param clazz
608 * a {@link java.lang.Class} object.
609 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
610 */
611 public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
612 String className = clazz.getName();
613 if (getBooleanValue(MATCH_STRATEGY_PREFIX + className, true)) {
614 IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
615
616 //TODO CacheMatchers (or multiple field matchers in future) are missing here
617 for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
618 String fieldName = fieldMatcher.getPropertyName();
619 String matchModeName = getStringValue(
620 getMatchStrategyFieldName(className, fieldName), true);
621 MatchMode matchMode = MatchMode.valueOf(matchModeName);
622 try {
623 matchStrategy.setMatchMode(fieldName, matchMode);
624 } catch (MatchException e) {
625 MessagingUtils.error(PreferencesUtil.class, e);
626 throw new RuntimeException(e);
627 }
628 }
629
630 return matchStrategy;
631 }
632 return getDefaultMatchStrategy(clazz);
633 }
634
635 /**
636 * Stores a matchStrategy into the preference store.
637 *
638 * @param matchStrategy
639 * a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
640 * object.
641 */
642 public static void setMatchStrategy(IMatchStrategy matchStrategy) {
643 String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
644 setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
645
646 List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
647
648 for (FieldMatcher fieldMatcher : fieldMatchers) {
649 String fieldName = fieldMatcher.getPropertyName();
650 setStringValue(
651 getMatchStrategyFieldName(className, fieldName),
652 fieldMatcher.getMatchMode().name());
653 }
654 }
655
656 /**
657 * Helper method to create the preference property for a match field.
658 *
659 * @param className
660 * @param fieldName
661 * @return
662 */
663 private static String getMatchStrategyFieldName(String className,
664 String fieldName) {
665 return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
666 }
667
668 /**
669 * Returns the default match strategy for a given class.
670 *
671 * @param clazz
672 * a {@link java.lang.Class} object.
673 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
674 */
675 public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
676 return DefaultMatchStrategy.NewInstance(clazz);
677 }
678
679 public static String getDateFormatPattern() {
680 // TODO make this configurable in properties
681 String pattern = "Y-M-d H:m";
682 return pattern;
683 }
684
685 public static <T extends TermBase> void addTermToPreferredTerms(T term) {
686
687 // VocabularyEnum vocabulary =
688 // VocabularyEnum.getVocabularyEnum(term.getClass());
689 //
690 // getPreferenceStore().setValue(getPreferenceKey(term),
691 // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
692 //
693 // firePreferencesChanged(term.getClass());
694 }
695
696 /**
697 * Construct a unique key using the CdmBase object's uuid
698 *
699 * @param cdmBase
700 * @return
701 */
702 private static String getPreferenceKey(ICdmBase cdmBase) {
703 cdmBase = HibernateProxyHelper.deproxy(cdmBase);
704
705 String key = cdmBase.getClass().getName().concat(".")
706 .concat(cdmBase.getUuid().toString());
707 if (key.contains("javassist")) { //Note by AM (2022-06): javassist is not used anymore, instead hibernate uses bytebuddy so this logging will not work anymore
708 MessagingUtils.info("proxy");
709 }
710 return key;
711 }
712
713 /**
714 * Construct a unique key using the CdmBase object's uuid
715 *
716 * @param cdmBase
717 * @return
718 */
719 public static String getPreferenceKey(ISimpleTerm<?> simpleTerm) {
720 simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
721 String key = simpleTerm.getClass().getName().concat(".")
722 .concat(simpleTerm.getUuid().toString());
723 if (key.contains("javassist")) { //Note by AM (2022-06): javassist is not used anymore, instead hibernate uses bytebuddy so this logging will not work anymore
724 MessagingUtils.warn(PreferencesUtil.class,
725 "Trying to persist a preference based on a proxy class.");
726 }
727 return key;
728 }
729
730 /**
731 * Construct a unique key using the CdmBase object's uuid
732 */
733 public static String getPreferenceKey(IDefinedTerm definedTerm) {
734 definedTerm = HibernateProxyHelper.deproxy(definedTerm);
735 String key = definedTerm.getClass().getName().concat(".")
736 .concat(definedTerm.getUuid().toString());
737 if (key.contains("javassist")) { //Note by AM (2022-06): javassist is not used anymore, instead hibernate uses bytebuddy so this logging will not work anymore
738 MessagingUtils.warn(PreferencesUtil.class,
739 "Trying to persist a preference based on a proxy class.");
740 }
741 return key;
742 }
743
744 /**
745 * Retrieves search preferences from the preference store
746 *
747 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
748 */
749 public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
750 IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
751
752 configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
753 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
754 configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
755 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
756 configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
757 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
758 configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
759 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
760 configurator.setDoIncludeAuthors(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS)? PreferencesUtil.getPreferenceStore().getBoolean(
761 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS): false);
762 configurator.setIncludeUnpublished(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_UNPUBLISHED)? PreferencesUtil.getPreferenceStore().getBoolean(
763 IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_UNPUBLISHED): true);
764 //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
765
766 return configurator;
767 }
768
769 /**
770 * create new preferences, setting all search options to true
771 *
772 * @return a
773 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
774 * object.
775 */
776 public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
777 IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
778
779 configurator.setDoTaxa(true);
780 configurator.setDoSynonyms(true);
781 configurator.setDoNamesWithoutTaxa(true);
782 configurator.setDoTaxaByCommonNames(true);
783 configurator.setIncludeUnpublished(true);
784 configurator.setDoIncludeAuthors(false);
785 configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
786 "name", "name.$", "relationsFromThisTaxon.$"));
787
788 configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
789 "name", "name.$", "synonyms.relatedTo.*"));
790
791 // DEFAULT VALUES
792 // match mode is a simple like, actually all other match modes are kind
793 // of bogus
794 configurator
795 .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
796 // we set page number and size here as this should always be unlimited
797 configurator.setPageNumber(0);
798 // TODO currently limit results to 10000
799 configurator.setPageSize(10000);
800 //setSearchConfigurator(configurator) ;
801 return configurator;
802 }
803
804 /**
805 * Store search preferences
806 *
807 * @param configurator
808 * a
809 * {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
810 * object.
811 */
812 public static void setSearchConfigurator(
813 IFindTaxaAndNamesConfigurator configurator) {
814 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
815 configurator.isDoTaxa());
816 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
817 configurator.isDoSynonyms());
818 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
819 configurator.isDoNamesWithoutTaxa());
820 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
821 configurator.isDoTaxaByCommonNames());
822 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS,
823 configurator.isDoIncludeAuthors());
824 getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_UNPUBLISHED,
825 configurator.isIncludeUnpublished());
826 }
827
828 public static void firePreferencesChanged(Class clazz) {
829 getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
830 null, clazz);
831 }
832
833 public static void firePreferencesChangedForNavigator() {
834 getPreferenceStore().firePropertyChangeEvent(UPDATE_NAVIGATOR,
835 null, null);
836 }
837
838
839 public static String createPreferenceString(String property){
840 return prefKey(property);
841 }
842 public static String createOverridePreferenceString(String property){
843 return prefOverrideKey(property);
844 }
845
846 public static boolean getOverrideForPreference(String preferenceString){
847 return PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(preferenceString), true);
848 }
849
850 /**
851 * Set default values for preferences
852 */
853 public static void setDefaults() {
854
855 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.EditMapServiceAccessPoint.getKey()),
856 "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
857 //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
858 getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
859 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
860 "http://www.biodiversitylibrary.org/openurl");
861 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
862 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
863 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
864 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
865 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
866 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
867 getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS, false);
868
869 //Name Details
870 // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
871
872 //Navigator preferences
873 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
874
875 //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
876
877 getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
878
879 getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
880 //override db preferences
881 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
882 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
883 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
884 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
885 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
886 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
887 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
888 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
889 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
890 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
891 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
892 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
893 getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
894 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
895 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifierFreeText.getKey())), false);
896 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifier.getKey())), false);
897 getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
898 }
899
900 public static void checkNomenclaturalCode() {
901 // First time Editor is opened, no nomenclatural code has been set
902 if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
903 PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
904 }
905 }
906
907 public static void setNomenclaturalCodePreferences(){
908 ICdmRepository controller;
909 controller = CdmStore.getCurrentApplicationConfiguration();
910 PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
911 CdmPreference preference = null;
912 if (controller == null){
913 return ;
914 }
915 preference = controller.getPreferenceService().find(key);
916 if (preference == null){
917 return;
918 }
919 // setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
920
921 int index = StringUtils.lastIndexOf(preference.getValue(), ".");
922 UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
923 NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
924
925 setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
926 getPreferenceKey(preferredCode));
927 }
928
929 public static void checkDefaultLanguage(){
930 if(PreferencesUtil.getPreferredDefaultLangugae() == null){
931 Shell shell = AbstractUtility.getShell();
932 int open = new DefaultLanguageDialog(shell).open();
933 if(open == Window.OK){
934 PlatformUI.getWorkbench().restart();
935 }
936 }else{
937 //TODO:In case of a reinstall, the config.ini will be overwritten
938 // here you create config.ini with the stored key from preferences
939 }
940 }
941
942 public static String getMapServiceAccessPoint() {
943 return getStringValue(PreferencePredicate.EditMapServiceAccessPoint.getKey());
944 }
945
946 public static boolean shouldConnectAtStartUp() {
947 //FIXME : force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
948 //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
949 return false;
950 }
951
952 public static TermTree<?> getDefaultFeatureTreeForTextualDescription() {
953 String uuidString = getStringValue(
954 FEATURE_TREE_DEFAULT_TEXT, true);
955 if (StringUtils.isBlank(uuidString)) {
956 return null;
957 }
958 TermTree<?> tree = CdmStore.getService(
959 ITermTreeService.class).load(UUID.fromString(uuidString));
960
961 if (tree == null || tree.getId() == 0) {
962 return null;
963 }
964 return tree;
965 }
966
967 public static TermTree<?> getDefaultFeatureTreeForStructuredDescription() {
968 String uuidString = getStringValue(
969 FEATURE_TREE_DEFAULT_STRUCTURE, true);
970 return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
971 ITermTreeService.class).load(UUID.fromString(uuidString));
972 }
973
974 public static void setSortRanksHierarchichally(boolean selection) {
975 setBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey(), selection);
976 }
977
978 public static boolean getSortRanksHierarchichally() {
979 return getBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey());
980 }
981
982 public static boolean isMultilanguageTextEditingCapability() {
983 return getBooleanValue(
984 PreferencePredicate.MultiLanguageTextEditing.getKey());
985 }
986
987 public static Language getGlobalLanguage() {
988
989 String languageUuidString = getStringValue(
990 GLOBAL_LANGUAGE_UUID, true);
991
992 if(!CdmStore.isActive()) {
993 MessagingUtils.noDataSourceWarningDialog(languageUuidString);
994 return null;
995 }
996
997 if (CdmUtils.isBlank(languageUuidString)) {
998 return Language.getDefaultLanguage();
999 }
1000
1001 UUID languageUuid = UUID.fromString(languageUuidString);
1002 return (Language) CdmStore.getService(ITermService.class).load(
1003 languageUuid);
1004 }
1005
1006 public static void setGlobalLanguage(Language language) {
1007 if(language != null) {
1008 setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1009 CdmStore.setDefaultLanguage(language);
1010 }
1011 }
1012
1013 public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1014 List<MarkerType> markerTypes = CdmStore.getTermManager()
1015 .getPreferredTerms(MarkerType.class);
1016
1017 Map<MarkerType, Boolean> result = new HashMap<>();
1018
1019 for (MarkerType markerType : markerTypes) {
1020 String name = getMarkerTypeEditingPreferenceKey(markerType);
1021 Boolean value = getBooleanValue(name);
1022 result.put(markerType, value);
1023 }
1024
1025 return result;
1026 }
1027
1028 public static void setEditMarkerTypePreferences(
1029 Map<MarkerType, Boolean> markerTypeEditingMap) {
1030 for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1031 String name = getMarkerTypeEditingPreferenceKey(markerType);
1032 setBooleanValue(name,
1033 markerTypeEditingMap.get(markerType));
1034 }
1035 }
1036
1037 private static String getMarkerTypeEditingPreferenceKey(
1038 MarkerType markerType) {
1039 markerType = HibernateProxyHelper.deproxy(markerType);
1040 return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1041 }
1042
1043 public static void setEditMarkerTypePreference(MarkerType markerType,
1044 boolean edit) {
1045 setBooleanValue(
1046 getMarkerTypeEditingPreferenceKey(markerType), edit);
1047 }
1048
1049 public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1050 DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1051 .NewInstance();
1052 configurator.setMoveDerivedUnitMediaToGallery(true);
1053 configurator.setMoveFieldObjectMediaToGallery(true);
1054 return configurator;
1055 }
1056
1057 /**
1058 * This method will write language properties to the config.ini located in the configuration folder
1059 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1060 *
1061 * @param setLanguage 0 is for german and 1 for english.
1062 * @throws IOException
1063 */
1064 public void writePropertyToConfigFile(int setLanguage) throws IOException {
1065 File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1066 //give warning to user if the directory has no write access
1067 if(file == null){
1068 throw new IOException();
1069 }
1070 Properties properties = load(file.getAbsolutePath()+"/config.ini");
1071 switch(setLanguage){
1072 case 0:
1073 properties.setProperty("osgi.nl", "de");
1074 setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1075 break;
1076 case 1:
1077 properties.setProperty("osgi.nl", "en");
1078 setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1079 break;
1080 default:
1081 break;
1082 }
1083 save(file+"/config.ini", properties);
1084 }
1085
1086 /**
1087 * This method loads a property from a given file and returns it.
1088 *
1089 * @param filename
1090 * @return
1091 * @throws IOException
1092 */
1093 private Properties load(String filename) throws IOException {
1094 FileInputStream in = new FileInputStream(filename);
1095 Properties prop = new Properties();
1096 prop.load(in);
1097 in.close();
1098 return prop;
1099 }
1100
1101 /**
1102 * This method saves a property to the specified file.
1103 *
1104 * @param filename
1105 * @param properties
1106 * @throws IOException
1107 */
1108 private void save(String filename, Properties properties) throws IOException{
1109 FileOutputStream fos = new FileOutputStream(filename);
1110 properties.store(fos, "");
1111 fos.close();
1112 }
1113
1114 /**
1115 * Saves a list of P2 Metadata Repositories as string with specified delimiters
1116 *
1117 * @param p2Repos
1118 */
1119 public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1120 StringBuilder sb = new StringBuilder();
1121 for(MetadataRepositoryElement p2Repo : p2Repos) {
1122 sb.append(P2_REPOSITORIES_DELIM);
1123 if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1124 sb.append("-");
1125 } else {
1126 sb.append(p2Repo.getName());
1127 }
1128 sb.append(P2_REPOSITORY_FIELDS_DELIM);
1129 sb.append(p2Repo.getLocation().toString());
1130 sb.append(P2_REPOSITORY_FIELDS_DELIM);
1131 sb.append(String.valueOf(p2Repo.isEnabled()));
1132 }
1133 getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1134 }
1135
1136
1137 /**
1138 * Retrieves a list of previously saved P2 repositories
1139 */
1140 public static List<MetadataRepositoryElement> getP2Repositories() {
1141 List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1142 String p2ReposPref = getStringValue(P2_REPOSITORY_LIST, true);
1143 if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1144 StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1145
1146 while(p2ReposPrefST.hasMoreTokens()) {
1147 String p2RepoStr = p2ReposPrefST.nextToken();
1148 StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1149 if(p2ReposStrST.countTokens()==3) {
1150 String nickname = p2ReposStrST.nextToken();
1151 URI uri = null;
1152 try {
1153 uri = new URI(p2ReposStrST.nextToken());
1154 } catch (URISyntaxException e) {
1155 continue;
1156 }
1157 boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1158 MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri.getJavaUri(), true);
1159 mre.setNickname(nickname);
1160 mre.setEnabled(enabled);
1161 p2Repos.add(mre);
1162 }
1163 }
1164 }
1165
1166 return p2Repos;
1167 }
1168
1169 /**
1170 * enables/disables nested composite. <br>
1171 *
1172 * @param ctrl - Composite to be en-/disabeld
1173 * @param enabled - boolean
1174 */
1175 public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1176 if (ctrl instanceof Composite) {
1177 Composite comp = (Composite) ctrl;
1178 for (Control c : comp.getChildren()) {
1179 recursiveSetEnabled(c, enabled);
1180 }
1181 } else {
1182 ctrl.setEnabled(enabled);
1183 }
1184 }
1185
1186 public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1187 if (nodesOrder == null){
1188 setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1189 }else{
1190 setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1191 }
1192 }
1193
1194 public static NavigatorOrderEnum getSortNodes() {
1195 return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1196 }
1197
1198 public static boolean isNodesSortedNaturally() {
1199 NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1200 return value.equals(NavigatorOrderEnum.NaturalOrder);
1201 }
1202
1203 public static boolean isNodesSortedByName() {
1204 NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1205 return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1206 }
1207
1208 public static boolean isNodesSortedByNameAndRank() {
1209 NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1210 return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1211 }
1212
1213 public static Comparator<TaxonNodeDto> getNodeComparator() {
1214 Comparator<TaxonNodeDto> comparator;
1215 NavigatorOrderEnum orderValue = NavigatorOrderEnum.RankAndNameOrder;
1216 try{
1217 orderValue = PreferencesUtil.getSortNodes();
1218 }catch(IllegalArgumentException e){
1219
1220 }
1221
1222 if (orderValue.equals(NavigatorOrderEnum.NaturalOrder)){
1223 comparator = new TaxonNodeDtoNaturalComparator();
1224 } else if (orderValue.equals(NavigatorOrderEnum.AlphabeticalOrder)){
1225 comparator = new TaxonNodeDtoByNameComparator();
1226 }else {
1227 comparator = new TaxonNodeDtoByRankAndNameComparator();
1228 }
1229 return comparator;
1230 }
1231
1232 public static boolean isStoreNavigatorState() {
1233 return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1234 }
1235
1236 public static void setStoreNavigatorState(boolean selection) {
1237 setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1238 }
1239
1240 public static boolean isShowUpWidgetIsDisposedMessages() {
1241 return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1242 }
1243
1244 public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1245 setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1246 }
1247
1248 public static boolean isShowIdInVocabularyInChecklistEditor() {
1249 String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1250 if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1251 return true;
1252 }else{
1253 return false;
1254 }
1255 }
1256 public static boolean isShowSymbol1InChecklistEditor() {
1257 String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1258 if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1259 return true;
1260 }else{
1261 return false;
1262 }
1263 }
1264 public static boolean isShowSymbol2InChecklistEditor() {
1265 String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1266 if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1267 return true;
1268 }else{
1269 return false;
1270 }
1271 }
1272
1273 public static void setAreaDisplayInChecklistEditor(String selection) {
1274 setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1275 }
1276
1277 public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1278 setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1279 }
1280
1281 public static boolean isOwnDescriptionForChecklistEditor() {
1282 return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1283 }
1284
1285 public static TermDisplayEnum displayAreaInChecklistEditor() {
1286 TermDisplayEnum result;
1287 try{
1288 result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1289 }catch (IllegalArgumentException e){
1290 result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1291 }
1292 return result;
1293 }
1294
1295 public static TermDisplayEnum displayStatusInChecklistEditor() {
1296 TermDisplayEnum result;
1297 try{
1298 result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1299 }catch (IllegalArgumentException e){
1300 result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1301 }
1302 return result;
1303 }
1304
1305 public static void setDisplayStatusInChecklistEditor(String selection) {
1306 setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1307 }
1308
1309 public static boolean isShowRankInChecklistEditor() {
1310 return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1311 }
1312
1313 public static void setShowRankInChecklistEditor(boolean selection) {
1314 setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1315 }
1316
1317 public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1318 NameDetailsConfigurator config = new NameDetailsConfigurator();
1319 CdmPreferenceCache cache = CdmPreferenceCache.instance();
1320 CdmPreference preference = null;
1321 String value;
1322 if (!local) {
1323 PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1324 preference = getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1325 if (preference == null){
1326 return null;
1327 }
1328
1329 // setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1330 value = preference.getValue();
1331 config.setAllowOverride(preference.isAllowOverride());
1332 //the preference value is build like this:
1333 //<section1>:true;<section2>:false....
1334 }else{
1335 value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1336 }
1337 if (value!= null){
1338 fillNameDetailsConfigurator(config, value);
1339
1340
1341 }else {
1342 return null;
1343 }
1344 return config;
1345 }
1346
1347 public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1348 String [] sections = value.split(";");
1349 Map<String, Boolean> sectionMap = new HashMap<>();
1350 String[] sectionValues;
1351 for (String sectionValue: sections){
1352 if (sectionValue.contains(":")){
1353 sectionValues = sectionValue.split(":");
1354 sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1355 }
1356 }
1357 for (Field field: config.getClass().getDeclaredFields()){
1358 try {
1359 config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1360 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1361 | SecurityException e) {
1362 logger.debug(e.getMessage());
1363 }
1364 }
1365 }
1366
1367 public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1368 NameDetailsConfigurator config = new NameDetailsConfigurator();
1369
1370 String value;
1371
1372 value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1373 if (value != null){
1374 fillNameDetailsConfigurator(config, value);
1375 }else {
1376 return null;
1377 }
1378 return config;
1379 }
1380
1381 public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1382 CdmPreference preference = null;
1383
1384 if (!local) {
1385 preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1386
1387 setPreferenceToDB(preference);
1388 }
1389 else{
1390 setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1391 }
1392 }
1393
1394 private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1395 if (sectionMap.containsKey(string)){
1396 return sectionMap.get(string);
1397 }else{
1398 return true;
1399 }
1400 }
1401
1402 public static void extractSecundumForSubtreeConfiguratorFromPreferenceString(SecundumForSubtreeConfigurator config,
1403 String configString) {
1404 if(configString != null){
1405 String[] configArray = configString.split(";");
1406
1407 for (String configItem: configArray){
1408 String[] keyValue = configItem.split(":");
1409 String keyString = keyValue[0];
1410 String valueString = null;
1411 if (keyValue.length>1){
1412 valueString = keyValue[1];
1413 if (keyValue.length>2){
1414
1415 for (int index = 2; index< keyValue.length; index++){
1416 valueString += ":"+ keyValue[index];
1417 }
1418 }
1419 }
1420 if (keyString.equals("includeAcceptedTaxa")){
1421 config.setIncludeAcceptedTaxa(Boolean.valueOf(valueString));
1422 }else if (keyString.equals("includeSynonyms")){
1423 config.setIncludeSynonyms(Boolean.valueOf(valueString));
1424 }else if (keyString.equals("includeSharedTaxa")){
1425 config.setIncludeSharedTaxa(Boolean.valueOf(valueString));
1426 }else if (keyString.equals("includeProParteSynonyms")){
1427 config.setIncludeProParteSynonyms(Boolean.valueOf(valueString));
1428 }else if (keyString.equals("includeMisapplications")){
1429 config.setIncludeMisapplications(Boolean.valueOf(valueString));
1430 }else if (keyString.equals("overwriteExisting")){
1431 config.setOverwriteExisting(Boolean.valueOf(valueString));
1432 }else if (keyString.equals("emptySecundumDetail")){
1433 config.setEmptySecundumDetail(Boolean.valueOf(valueString));
1434 }else{
1435 logger.debug("This key of the set secundum configurator needs to be added to the transformer: " + keyString);
1436 }
1437 }
1438 }
1439 }
1440
1441 public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1442
1443 Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1444 ICdmRepository controller;
1445 controller = CdmStore.getCurrentApplicationConfiguration();
1446 PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1447 CdmPreference preference = null;
1448 if (controller == null){
1449 return null;
1450 }
1451 preference = controller.getPreferenceService().find(key);
1452 if (preference == null){
1453 return config;
1454 } else{
1455 String configString = preference.getValue();
1456 extractAbcdConfiguratorFromPreferenceString(config, configString);
1457 }
1458 return config;
1459 }
1460
1461 public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1462 String configString) {
1463 if(configString != null){
1464 String[] configArray = configString.split(";");
1465
1466 for (String configItem: configArray){
1467 String[] keyValue = configItem.split(":");
1468 String keyString = keyValue[0];
1469 String valueString = null;
1470 if (keyValue.length>1){
1471 valueString = keyValue[1];
1472 if (keyValue.length>2){
1473
1474 for (int index = 2; index< keyValue.length; index++){
1475 valueString += ":"+ keyValue[index];
1476 }
1477 }
1478 }
1479 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1480 config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1481 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1482 config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1483 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1484 config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1485 }else if (keyString.equals("ignoreAuthorship")){
1486 config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1487 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1488 config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1489 }else if (keyString.equals("reuseExistingMetaData")){
1490 config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1491 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1492 config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1493 }else if (keyString.equals("allowReuseOtherClassifications")){
1494 config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1495 }else if (keyString.equals("deduplicateReferences")){
1496 config.setDeduplicateReferences(Boolean.valueOf(valueString));
1497 }else if (keyString.equals("deduplicateClassifications")){
1498 config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1499 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1500 config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1501 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1502 config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1503 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1504 config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1505 }else if (keyString.equals("mapUnitIdToBarcode")){
1506 config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1507 }else if (keyString.equals("overwriteExistingSpecimens")){
1508 config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1509 }else if (keyString.equals("nomenclaturalCode")){
1510 config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1511 }else if (keyString.equals("removeCountryFromLocalityText")){
1512 config.setRemoveCountryFromLocalityText(Boolean.valueOf(valueString));
1513 }else if (keyString.equals("getSiblings")){
1514 config.setGetSiblings(Boolean.valueOf(valueString));
1515 }else if (keyString.equals("classificationUUID")){
1516 if (valueString != null){
1517 config.setClassificationUuid(UUID.fromString(valueString));
1518 }
1519 }else if (keyString.equals("classificationName")){
1520 config.setClassificationName(valueString);
1521 }else if (keyString.equals("dnaSource")){
1522 try{
1523 if (StringUtils.isNotBlank(valueString)){
1524 config.setDnaSoure(URI.create(valueString));
1525 }
1526 }catch(Exception e){
1527 config.setDnaSoure(null);
1528 }
1529 }else{
1530 logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1531 }
1532 }
1533 }
1534 }
1535
1536 public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1537 return getLocalAbcdImportConfigurator(true);
1538 }
1539
1540 public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1541 Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1542 CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1543 if (pref == null || pref.isAllowOverride()){
1544 String configString = PreferencesUtil.getStringValue(PreferencePredicate.AbcdImportConfig.getKey());
1545 if (StringUtils.isBlank(configString)){
1546 configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1547 extractAbcdConfiguratorFromPreferenceString(config, configString);
1548 if (config.getNomenclaturalCode() == null){
1549 config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1550 }
1551 }else{
1552 config = Abcd206ImportConfigurator.NewInstance(null, null);
1553 PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1554 }
1555 }else{
1556 extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1557 }
1558
1559 return config;
1560
1561 }
1562
1563 public static Abcd206ImportConfigurator getLastUsedAbcdImportConfigurator(){
1564 Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1565
1566 String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG, true);
1567 if (configString != null){
1568 extractAbcdConfiguratorFromPreferenceString(config, configString);
1569 if (config != null){
1570 if (config.getNomenclaturalCode() == null){
1571 config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1572 }
1573 }
1574 }else{
1575 config = PreferencesUtil.getLocalAbcdImportConfigurator(false);
1576 }
1577
1578 return config;
1579
1580 }
1581
1582 public static void updateAbcdImportConfigurationPreference() {
1583 CdmPreferenceCache cache = CdmPreferenceCache.instance();
1584
1585 CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1586
1587 if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1588 resetToDBPreferenceAbcdCOnfigurator();
1589
1590 }
1591 }
1592
1593 public static void resetToDBPreferenceAbcdCOnfigurator(){
1594 Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1595 setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1596 }
1597
1598 public static boolean isSortTaxaByRankAndName() {
1599 return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1600 }
1601
1602 public static TermOrder getSortNamedAreasInDistributionEditor() {
1603 TermOrder result;
1604 try{
1605 result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1606 }catch (IllegalArgumentException e){
1607 result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1608 }
1609 return result;
1610 }
1611
1612 public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1613 setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1614 }
1615
1616 public static void setLastSelectedReference(
1617 List<String> lastSelectedReferences) {
1618
1619 setStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1620 }
1621
1622 public static List<String> getLastSelectedReferences() {
1623
1624 //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1625 String lastSelected = getStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, true);
1626 List<String> result = new ArrayList<>();
1627 if (!StringUtils.isBlank(lastSelected)){
1628 Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1629 }
1630 return result;
1631 }
1632
1633 public static void setPreferredNamedAreasForDistributionEditor(
1634 String saveCheckedElements, String saveGrayedElements, boolean local) {
1635 if (local){
1636 setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1637 }
1638 else{
1639 CdmPreference preference = null;
1640
1641 if (saveCheckedElements == null){
1642 preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1643
1644 if (preference == null){
1645 return ;
1646 } else{
1647 setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1648 saveCheckedElements);
1649 preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1650 setPreferenceToDB(preference);
1651
1652 }
1653 } else{
1654 preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1655 setPreferenceToDB(preference);
1656 setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1657 saveCheckedElements);
1658
1659 }
1660 }
1661 }
1662
1663 public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1664 boolean local, boolean isOverride) {
1665 if (local){
1666 setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1667 setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1668 }
1669 else{
1670 CdmPreference preference = null;
1671
1672 if (saveCheckedElements == null){
1673 preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1674
1675 if (preference == null){
1676 return ;
1677 } else{
1678 setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1679 saveCheckedElements);
1680 preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1681 preference.setAllowOverride(isOverride);
1682 setPreferenceToDB(preference);
1683 }
1684 } else{
1685 preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1686 preference.setAllowOverride(isOverride);
1687 setPreferenceToDB(preference);
1688 setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1689 saveCheckedElements);
1690 }
1691 }
1692 }
1693
1694 public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1695 if (local){
1696
1697 String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1698 return pref;
1699 }
1700 else{
1701 CdmPreference preference = null;
1702 preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1703 if (preference == null){
1704 return null;
1705 } else{
1706 return preference.getValue();
1707 }
1708 }
1709 }
1710
1711 public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1712 if (prefKey == null){
1713 return null;
1714 }
1715 String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1716 if (prefValue == null){
1717 return null;
1718 }
1719 List<UUID> uuidList = createUuidList(prefValue);
1720 return uuidList;
1721 }
1722
1723 public static List<UUID> createUuidList(String prefValue) {
1724 String[] stringArray = prefValue.split(";");
1725 List<UUID> uuidList = new ArrayList<>();
1726 for (String uuid: stringArray){
1727 if (!StringUtils.isBlank(uuid)){
1728 uuidList.add(UUID.fromString(uuid));
1729 }
1730 }
1731 return uuidList;
1732 }
1733
1734 public static boolean getFilterCommonNameReferences(){
1735 return getBooleanValue(PreferencePredicate.CommonNameReferencesWithMarker.getKey());
1736 }
1737
1738 public static void updateDBPreferences() {
1739
1740 CdmPreferenceCache cache = CdmPreferenceCache.instance();
1741 cache.getAllTaxEditorDBPreferences();
1742
1743 //Name Details
1744 NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1745
1746 }
1747
1748 public static void setPreferencesToDB(List<CdmPreference> preferences) {
1749
1750 ICdmRepository controller;
1751 if(CdmStore.isActive()){
1752 controller = CdmStore.getCurrentApplicationConfiguration();
1753 for (CdmPreference preference: preferences){
1754 if (preference.getValue() == null && preference.isAllowOverride()){
1755 controller.getPreferenceService().remove(preference.getKey());
1756
1757 }else{
1758 controller.getPreferenceService().set(preference);
1759
1760 }
1761
1762 }
1763 CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1764 }
1765 }
1766
1767 /**
1768 * Returns whether the named preference is known.
1769 * @param prefKey the key of the preference
1770 * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1771 */
1772 public static boolean contains(String prefKey){
1773 return getPreferenceStore().contains(prefKey(prefKey));
1774 }
1775
1776 /**
1777 *
1778 */
1779 public static TermTree<?> getPreferredFeatureTreeForNameDescription(boolean createNew) {
1780 if(preferredNameFeatureTree != null && !createNew){
1781 return preferredNameFeatureTree;
1782 }
1783 createPreferredFeatureTreeForNameDescription();
1784 return preferredNameFeatureTree;
1785 }
1786
1787 public static void createPreferredFeatureTreeForNameDescription() {
1788
1789 CdmPreferenceCache cache = CdmPreferenceCache.instance();
1790 CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1791 List<Feature> terms = new ArrayList<>();
1792 boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.NameFeatures.getKey());
1793
1794 List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1795 if (uuids != null && !uuids.isEmpty()){
1796 terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1797 }
1798
1799 if (terms.isEmpty()){
1800 terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1801 }
1802 terms.remove(Feature.PROTOLOGUE());
1803 if (terms.isEmpty()){
1804 preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1805 }else{
1806 preferredNameFeatureTree = TermTree.NewInstance(terms);
1807 }
1808 }
1809
1810 public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1811 ICdmRepository controller;
1812 //try{
1813 if(CdmStore.isActive()){
1814 controller = CdmStore.getCurrentApplicationConfiguration();
1815 for (CdmPreference preference: prefsToDelete){
1816 controller.getPreferenceService().remove(preference.getKey());
1817 }
1818 CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1819 }
1820 }
1821
1822 public static void removeFromDB(CdmPreference prefToDelete) {
1823 ICdmRepository controller;
1824
1825 if(CdmStore.isActive()){
1826 controller = CdmStore.getCurrentApplicationConfiguration();
1827 controller.getPreferenceService().remove(prefToDelete.getKey());
1828
1829 CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1830 }
1831 }
1832
1833 public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1834 if(preferredTaxonFeatureTree != null && !createNew){
1835 return preferredTaxonFeatureTree;
1836 }
1837 createPreferredFeatureTreeForTaxonDescription();
1838 return preferredTaxonFeatureTree;
1839 }
1840
1841 public static void createPreferredFeatureTreeForTaxonDescription() {
1842
1843 CdmPreferenceCache cache = CdmPreferenceCache.instance();
1844 CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1845 List<Feature> terms = null;
1846 boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.TaxonFeatures.getKey());
1847 List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1848 if (uuids != null && !uuids.isEmpty()){
1849 terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1850 }
1851 if (terms == null || terms.isEmpty()){
1852 terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1853 TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1854 Set<Feature> nameFeature = nameVocabulary.getTerms();
1855 terms.removeAll(nameFeature);
1856
1857 }
1858
1859 if (terms.isEmpty()){
1860 preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1861 }else{
1862 preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1863 }
1864 }
1865
1866 public static void setLastSelectedBiocaseProvider(String lastAccessPoint) {
1867 setStringValue(LAST_USED_BIOCASE_PROVIDER, lastAccessPoint);
1868 }
1869
1870 /**
1871 * @return
1872 */
1873 public static boolean getLocalActive() {
1874 // TODO: this needs to be adapted!!!
1875 return true;
1876 }
1877
1878 /**
1879 * @return
1880 */
1881 public static boolean showGfbioMetaData() {
1882 //TODO: needs to be adapted!!!
1883 return false;
1884 }
1885
1886 public static SecReferenceHandlingEnum getSecReferenceHandlingPreference(){
1887
1888 String defaultBehaviour = getStringValue(PreferencePredicate.DefaultBehaviourForSecundum.getKey());
1889 SecReferenceHandlingEnum handling = null;
1890 try{
1891 handling = SecReferenceHandlingEnum.valueOf(defaultBehaviour);
1892 }catch(IllegalArgumentException e){
1893 handling = (SecReferenceHandlingEnum)PreferencePredicate.DefaultBehaviourForSecundum.getDefaultValue();
1894 }
1895 return handling;
1896
1897 }
1898
1899 public static SecReferenceHandlingSwapEnum getSecReferenceHandlingSwapPreference(){
1900 String defaultBehaviour = getStringValue(PreferencePredicate.DefaultBehaviourForSecundumWhenSwap.getKey());
1901 SecReferenceHandlingSwapEnum handling = null;
1902 try{
1903 handling = SecReferenceHandlingSwapEnum.valueOf(defaultBehaviour);
1904 }catch (IllegalArgumentException e){
1905 handling = (SecReferenceHandlingSwapEnum)PreferencePredicate.DefaultBehaviourForSecundumWhenSwap.getDefaultValue();
1906 }
1907 return handling;
1908
1909 }
1910
1911 public static EnabledComputedDescription getComputedDesciptionHandlingPreference(){
1912 String defaultBehaviour= getStringValue(PreferencePredicate.EnableComputedDescription.getKey());
1913 EnabledComputedDescription computedDescriptionsEnabled = (EnabledComputedDescription)PreferencePredicate.EnableComputedDescription.getDefaultValue();
1914 if (StringUtils.isNotBlank(defaultBehaviour)){
1915 try{
1916 computedDescriptionsEnabled = EnabledComputedDescription.byKey(defaultBehaviour);
1917 }catch(IllegalArgumentException e){
1918 //do nothing, keep default value;
1919 }
1920 }
1921 return computedDescriptionsEnabled;
1922
1923 }
1924
1925 public static boolean isComputedDesciptionHandlingDisabled(){
1926 String defaultBehaviour= getStringValue(PreferencePredicate.EnableComputedDescription.getKey());
1927 EnabledComputedDescription computedDescriptionsEnabled = null;
1928 try{
1929 computedDescriptionsEnabled = EnabledComputedDescription.byKey(defaultBehaviour);
1930 }catch (IllegalArgumentException e){
1931 computedDescriptionsEnabled = (EnabledComputedDescription)PreferencePredicate.EnableComputedDescription.getDefaultValue();
1932 }
1933 return computedDescriptionsEnabled.equals(EnabledComputedDescription.Disabled);
1934
1935 }
1936
1937 }