1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.form.field.transformer.basic;
35
36 import info.magnolia.objectfactory.Components;
37 import info.magnolia.ui.api.i18n.I18NAuthoringSupport;
38 import info.magnolia.ui.form.field.definition.ConfiguredFieldDefinition;
39 import info.magnolia.ui.form.field.definition.OptionGroupFieldDefinition;
40
41 import java.util.Collection;
42 import java.util.HashSet;
43 import java.util.LinkedList;
44 import java.util.List;
45 import java.util.Set;
46
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.vaadin.v7.data.Item;
51 import com.vaadin.v7.data.Property;
52
53
54
55
56
57
58
59
60
61
62
63 public class ListToSetTransformer<T> extends BasicTransformer<T> {
64
65 private static final Logger log = LoggerFactory.getLogger(ListToSetTransformer.class);
66
67 private final boolean multiselect;
68
69
70
71
72 @Deprecated
73 public ListToSetTransformer(Item relatedFormItem, ConfiguredFieldDefinition definition, Class<T> type) {
74 this(relatedFormItem, definition, type, Components.getComponent(I18NAuthoringSupport.class));
75 }
76
77 public ListToSetTransformer(Item relatedFormItem, ConfiguredFieldDefinition definition, Class<T> type, I18NAuthoringSupport i18NAuthoringSupport) {
78 super(relatedFormItem, definition, type, i18NAuthoringSupport);
79 if (definition instanceof OptionGroupFieldDefinition) {
80 multiselect = ((OptionGroupFieldDefinition) definition).isMultiselect();
81 } else {
82 multiselect = false;
83 log.info("ListToSetTransformer is intended for multiselect OptionGroupFieldDefinition, but definition was of type {}. This may behave like a plain BasicTransformer.", definition);
84 }
85 }
86
87 @Override
88 public void writeToItem(T newValue) {
89 if (!multiselect) {
90 super.writeToItem(newValue);
91 return;
92 }
93
94 Property<T> p = getOrCreateProperty(type, false);
95 if (isCollectionConversionNeeded(newValue, p.getType())) {
96 newValue = (T) new LinkedList((Set) newValue);
97 }
98 if (newValue instanceof Collection && ((Collection) newValue).isEmpty()) {
99 newValue = null;
100 }
101 p.setValue(newValue);
102 }
103
104
105
106
107 protected boolean isCollectionConversionNeeded(T newValue, Class<?> propertyType) {
108 return List.class.isAssignableFrom(propertyType) && newValue instanceof Set;
109 }
110
111 @Override
112 public T readFromItem() {
113 if (!multiselect) {
114 return super.readFromItem();
115 }
116
117 Property<T> p = getOrCreateProperty(type, false);
118 if (definition.isReadOnly()) {
119 p.setReadOnly(true);
120 }
121 T value = p.getValue();
122 if (value != null && value instanceof List) {
123 return (T) new HashSet((List) value);
124 }
125 return null;
126 }
127
128 }