Ravi Srinivasan
2018-09-10 41d5004b9e40b9e29b37c26cbd1c154b97e2fe7a
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.redhat.training.ui;
 
import java.util.Set;
import java.util.function.Predicate;
 
import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
 
import com.redhat.training.model.UserGroup;
 
@FacesConverter(value = "SelectItemToEntityConverter")
public class SelectItemConverter implements Converter {
 
    @Override
    public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
        Object o = null;
        if (!(value == null || value.isEmpty())) {
            o = this.getSelectedItemAsEntity(comp, value);
        }
        return o;
    }
 
    @Override
    public String getAsString(FacesContext ctx, UIComponent comp, Object value) {
        String s = "";
        if (value != null) {
            s = ((UserGroup) value).getId().toString();
        }
        return s;
    }
 
    private UserGroup getSelectedItemAsEntity(UIComponent comp, String value) {
        UserGroup item = null;
 
        Set<UserGroup> selectItems = null;
        for (UIComponent uic : comp.getChildren()) {
            if (uic instanceof UISelectItems) {
                Long itemId = Long.valueOf(value);
                selectItems = (Set<UserGroup>) ((UISelectItems) uic).getValue();
 
                if (itemId != null && selectItems != null && !selectItems.isEmpty()) {
                    Predicate<UserGroup> predicate = i -> i.getId().equals(itemId);
                    item = selectItems.stream().filter(predicate).findFirst().orElse(null);
                }
            }
        }
 
        return item;
    }
}