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