Ravi Srinivasan
2018-09-10 41d5004b9e40b9e29b37c26cbd1c154b97e2fe7a
commit | author | age
41d500 1 package com.redhat.training.ui;
RS 2
3 import java.util.Set;
4 import java.util.function.Predicate;
5
6 import javax.faces.component.UIComponent;
7 import javax.faces.component.UISelectItems;
8 import javax.faces.context.FacesContext;
9 import javax.faces.convert.Converter;
10 import javax.faces.convert.FacesConverter;
11
12 import com.redhat.training.model.UserGroup;
13
14 @FacesConverter(value = "SelectItemToEntityConverter")
15 public class SelectItemConverter implements Converter {
16
17     @Override
18     public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
19         Object o = null;
20         if (!(value == null || value.isEmpty())) {
21             o = this.getSelectedItemAsEntity(comp, value);
22         }
23         return o;
24     }
25
26     @Override
27     public String getAsString(FacesContext ctx, UIComponent comp, Object value) {
28         String s = "";
29         if (value != null) {
30             s = ((UserGroup) value).getId().toString();
31         }
32         return s;
33     }
34
35     private UserGroup getSelectedItemAsEntity(UIComponent comp, String value) {
36         UserGroup item = null;
37
38         Set<UserGroup> selectItems = null;
39         for (UIComponent uic : comp.getChildren()) {
40             if (uic instanceof UISelectItems) {
41                 Long itemId = Long.valueOf(value);
42                 selectItems = (Set<UserGroup>) ((UISelectItems) uic).getValue();
43
44                 if (itemId != null && selectItems != null && !selectItems.isEmpty()) {
45                     Predicate<UserGroup> predicate = i -> i.getId().equals(itemId);
46                     item = selectItems.stream().filter(predicate).findFirst().orElse(null);
47                 }
48             }
49         }
50
51         return item;
52     }
53 }