1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.peaseplate.internal.lang.command;
21
22 import java.lang.reflect.Field;
23 import java.lang.reflect.Method;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.peaseplate.TemplateRuntimeException;
28 import org.peaseplate.internal.BuildContext;
29 import org.peaseplate.internal.util.ReflectionException;
30 import org.peaseplate.internal.util.ReflectionUtils;
31 import org.peaseplate.locator.TemplateLocator;
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 public class QueryCommand extends AbstractObjectCallCommand {
60
61 private final ICommand identifierCommand;
62
63 public QueryCommand(TemplateLocator locator, int line, int column, ICommand command, ICommand identifierCommand, ICommand[] parameterCommands) {
64 super(locator, line, column, command, parameterCommands);
65
66 this.identifierCommand = identifierCommand;
67 }
68
69
70
71
72 public Object call(BuildContext context) throws TemplateRuntimeException {
73 Object workingObject = callCommand(context);
74
75 if (workingObject == null)
76 return null;
77
78 return callObject(context, workingObject, identifierCommand.call(context));
79 }
80
81
82
83
84 @Override
85 protected Object callObject(BuildContext context, Object onObject, Object identifier) throws TemplateRuntimeException {
86 if (onObject == null)
87 return null;
88
89 if (onObject instanceof Map)
90 return callMap(context, (Map<?, ?>)onObject, identifier);
91
92 else if ((onObject instanceof List) && (identifier instanceof Number))
93 return callList((List<?>)onObject, ((Number)identifier).intValue());
94
95 else if ((onObject.getClass().isArray()) && (identifier instanceof Number))
96 return callArray((Object[])onObject, ((Number)identifier).intValue());
97
98 return callFieldOrMethod(context, onObject, String.valueOf(identifier));
99 }
100
101
102
103
104 @Override
105 protected Field getField(Class<?> clazz, String identifier) throws TemplateRuntimeException {
106 return findField(clazz, identifier);
107 }
108
109
110
111
112 @Override
113 protected Method getMethod(Class<?> clazz, String identifier, int numberOfParameters) throws TemplateRuntimeException {
114 try {
115 return ReflectionUtils.findMethod(clazz, identifier, numberOfParameters);
116 }
117 catch (ReflectionException e) {
118 throw new TemplateRuntimeException(
119 getLocator(), getLine(), getColumn(),
120 "Could not find method \"" + identifier + "\" in " + clazz, e
121 );
122 }
123 }
124
125
126
127
128 @Override
129 public String toString() {
130 StringBuilder result = new StringBuilder();
131
132 if (getCommand() != null)
133 result.append(getCommand());
134
135 result.append("[").append(identifierCommand).append("]");
136 result.append(super.toString());
137
138 return result.toString();
139 }
140
141 }