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