fixing NPE
[cdm-vaadin.git] / src / main / java / eu / etaxonomy / cdm / vaadin / util / CdmVaadinUtilities.java
1 /**
2 * Copyright (C) 2015 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 package eu.etaxonomy.cdm.vaadin.util;
10
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Set;
14
15 import com.vaadin.ui.AbstractSelect;
16 import com.vaadin.ui.Component;
17 import com.vaadin.ui.HasComponents;
18 import com.vaadin.ui.UI;
19
20 import eu.etaxonomy.cdm.vaadin.component.CdmProgressComponent;
21
22 /**
23 * @author cmathew
24 * @since 7 Apr 2015
25 *
26 */
27 public class CdmVaadinUtilities {
28
29 /**
30 * Thread safe method to asynchronously perform an update.
31 *
32 * @param update
33 */
34 public static void asyncExec(Runnable update) {
35 UI currentUI = UI.getCurrent();
36 Thread t = new Thread(update);
37 if(currentUI != null) {
38 synchronized(currentUI) {
39 t.start();
40 }
41 } else {
42 throw new UnsupportedOperationException("Cannot execute update on a UI which is null");
43 }
44 }
45
46 public static void exec(CdmVaadinOperation op) {
47 if(op.isAsync()) {
48 asyncExec(op);
49 } else {
50 op.run();
51 }
52 }
53
54
55 public static void setEnabled(Component root, boolean isEnabled, List<? extends Component> exceptions) {
56 if(exceptions != null && exceptions.contains(root)) {
57 return;
58 }
59 if(root instanceof HasComponents) {
60 HasComponents hc = (HasComponents) root;
61 Iterator<Component> iterator = hc.iterator();
62 while(iterator.hasNext()) {
63 setEnabled(iterator.next(), isEnabled, exceptions);
64 }
65 } else {
66 root.setEnabled(isEnabled);
67 }
68 }
69
70 public static void enableOnlyProgressBar(Component component) {
71 if(component instanceof CdmProgressComponent) {
72 component.setEnabled(true);
73 return;
74 }
75 if(component instanceof HasComponents) {
76 HasComponents hc = (HasComponents) component;
77 Iterator<Component> iterator = hc.iterator();
78 while(iterator.hasNext()) {
79 enableOnlyProgressBar(iterator.next());
80 }
81 } else {
82 component.setEnabled(false);
83 }
84 }
85
86 public static boolean isSelected(AbstractSelect select, Object itemId) {
87 if(select.getValue() != null) {
88 if(select.isMultiSelect()) {
89 Set<Object> selectedItemIds = (Set<Object>)select.getValue();
90 for(Object selectedItemId : selectedItemIds) {
91 if(selectedItemId.equals(itemId)) {
92 return true;
93 }
94 }
95 } else {
96 return (select.getValue().equals(itemId));
97 }
98 }
99 return false;
100 }
101
102
103 }