01 /*
02 * Copyright 2008-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package griffon.pivot.support;
17
18 import griffon.exceptions.InstanceMethodInvocationException;
19 import org.apache.pivot.wtk.Component;
20 import org.apache.pivot.wtk.Container;
21
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24
25 import static griffon.util.GriffonClassUtils.invokeExactInstanceMethod;
26 import static griffon.util.GriffonNameUtils.requireNonBlank;
27 import static java.util.Objects.requireNonNull;
28
29 /**
30 * @author Andres Almiray
31 * @since 2.0.0
32 */
33 public class PivotUtils {
34 private PivotUtils() {
35 // prevent instantiation
36 }
37
38 /**
39 * Searches a component by name in a particular component hierarchy.<p>
40 * A component must have a value for its <tt>name</tt> property if it's
41 * to be found with this method.<br/>
42 * This method performs a depth-first search.
43 *
44 * @param name the value of the component's <tt>name</tt> property
45 * @param root the root of the component hierarchy from where searching
46 * searching should start
47 *
48 * @return the component reference if found, null otherwise
49 */
50 @Nullable
51 public static Component findComponentByName(@Nonnull String name, @Nonnull Container root) {
52 requireNonNull(root, "Argument 'root' must not be null");
53 requireNonBlank(name, "Argument 'name' must not be blank");
54 if (name.equals(root.getName())) {
55 return root;
56 }
57
58 for (Component comp : root) {
59 if (name.equals(comp.getName())) {
60 return comp;
61 }
62 if (comp instanceof Container) {
63 Component found = findComponentByName(name, (Container) comp);
64 if (found != null) {
65 return found;
66 }
67 }
68 }
69
70 // finally attempt calling getContent()
71 try {
72 Component component = (Component) invokeExactInstanceMethod(root, "getContent");
73 if (component != null) {
74 if (name.equals(component.getName())) {
75 return component;
76 } else if (component instanceof Container) {
77 return findComponentByName(name, (Container) component);
78 }
79 }
80 } catch (InstanceMethodInvocationException imie) {
81 // ignore
82 }
83
84 return null;
85 }
86 }
|