forked from lincolnthree/aerogear-controller
/
ParameterExtractor.java
196 lines (178 loc) · 9.33 KB
/
ParameterExtractor.java
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.controller.util;
import br.com.caelum.iogi.Iogi;
import br.com.caelum.iogi.reflection.Target;
import br.com.caelum.iogi.util.DefaultLocaleProvider;
import br.com.caelum.iogi.util.NullDependencyProvider;
import com.google.common.base.Optional;
import org.jboss.aerogear.controller.log.AeroGearLogger;
import org.jboss.aerogear.controller.log.LoggerMessages;
import org.jboss.aerogear.controller.router.Consumer;
import org.jboss.aerogear.controller.router.RouteContext;
import org.jboss.aerogear.controller.router.rest.pagination.PaginationInfo;
import org.jboss.aerogear.controller.util.StringUtils;
import org.jboss.aerogear.controller.router.parameter.Parameter;
import org.jboss.aerogear.controller.router.parameter.RequestParameter;
import javax.servlet.http.Cookie;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class ParameterExtractor {
private static final Iogi IOGI = new Iogi(new NullDependencyProvider(), new DefaultLocaleProvider());
/**
* Extracts the arguments from the current request for the target route.
*
* @param routeContext the {@link org.jboss.aerogear.controller.router.RouteContext}.
* @return {@code Object[]} an array of Object matching the route targets parameters.
*/
public static Map<String, Object> extractArguments(final RouteContext routeContext, final Map<String, Consumer> consumers) throws Exception {
final Map<String, Object> args = new LinkedHashMap<String, Object>();
for (Parameter<?> parameter : routeContext.getRoute().getParameters()) {
switch (parameter.getParameterType()) {
case ENTITY:
if (PaginationInfo.class.isAssignableFrom(parameter.getType())) {
break;
}
if (!addIfPresent(extractIogiParam(routeContext), "entity", args)) {
args.put("entity", extractBody(routeContext, parameter, consumers));
}
break;
case REQUEST:
final RequestParameter<?> requestParameter = (RequestParameter<?>) parameter;
if (addIfPresent(extractParam(routeContext, requestParameter), requestParameter.getName(), args)) {
break;
}
if (addIfPresent(extractHeaderParam(routeContext, requestParameter), requestParameter.getName(), args)) {
break;
}
if (addIfPresent(extractCookieParam(routeContext, requestParameter), requestParameter.getName(), args)) {
break;
}
if (addIfPresent(extractDefaultParam(requestParameter), requestParameter.getName(), args)) {
break;
}
if (addIfPresent(extractPathParam(routeContext, parameter.getType()), requestParameter.getName(), args)) {
break;
}
throw LoggerMessages.MESSAGES.missingParameterInRequest(requestParameter.getName());
}
}
return args;
}
private static Optional<?> extractDefaultParam(RequestParameter<?> requestParameter) throws Exception {
if(requestParameter.getDefaultValue().isPresent()) {
return Optional.of(createInstance(requestParameter.getType(), requestParameter.getDefaultValue().get().toString()));
}
return requestParameter.getDefaultValue();
}
private static Object extractBody(final RouteContext routeContext, final Parameter<?> parameter,
final Map<String, Consumer> consumers) {
final Set<String> mediaTypes = routeContext.getRoute().consumes();
for (String mediaType : mediaTypes) {
final Consumer consumer = consumers.get(mediaType);
if (consumer != null) {
return consumer.unmarshall(routeContext.getRequest(), parameter.getType());
}
}
throw LoggerMessages.MESSAGES.noConsumerForMediaType(parameter, consumers.values(), mediaTypes);
}
/**
* Extracts a path parameter from the passed in request path.
*
*
* @param routeContext the {@link org.jboss.aerogear.controller.router.RouteContext} to extract a path parameter from.
* @param type
* @return {@code Optional<String>} containing the extracted path param if present in the request path.
*/
public static Optional<?> extractPathParam(final RouteContext routeContext, Class<?> type) throws Exception {
final String requestPath = routeContext.getRequestPath();
final int paramOffset = routeContext.getRoute().getPath().indexOf('{');
if (paramOffset != -1 && paramOffset < requestPath.length()) {
String pathParam = requestPath.subSequence(paramOffset, requestPath.length()).toString();
return Optional.of(createInstance(type, pathParam));
}
return Optional.absent();
}
/**
* Returns an instance of the type used in the parameter names using Iogi. </p> For example, having form parameters named
* 'car.color', 'car.brand', this method would try to use those values to instantiate a new Car instance.
*
* @return {@link com.google.common.base.Optional} may contain the instantiated instance, else isPresent will return false.
*/
public static Optional<?> extractIogiParam(final RouteContext routeContext) {
final LinkedList<br.com.caelum.iogi.parameters.Parameter> parameters = new LinkedList<br.com.caelum.iogi.parameters.Parameter>();
for (Map.Entry<String, String[]> entry : routeContext.getRequest().getParameterMap().entrySet()) {
final String[] value = entry.getValue();
if (value.length == 1) {
parameters.add(new br.com.caelum.iogi.parameters.Parameter(entry.getKey(), value[0]));
} else {
AeroGearLogger.LOGGER.multivaluedParamsUnsupported();
}
}
if (!parameters.isEmpty()) {
final Class<?>[] parameterTypes = routeContext.getRoute().getTargetMethod().getParameterTypes();
final Class<?> parameterType = parameterTypes[0];
final Target<?> target = Target.create(parameterType, StringUtils.downCaseFirst(parameterType.getSimpleName()));
return Optional.fromNullable(IOGI.instantiate(target,
parameters.toArray(new br.com.caelum.iogi.parameters.Parameter[parameters.size()])));
}
return Optional.absent();
}
private static boolean addIfPresent(final Optional<?> op, final String paramName, final Map<String, Object> args) {
if (op.isPresent()) {
args.put(paramName, op.get());
return true;
}
return false;
}
private static Optional<?> extractHeaderParam(final RouteContext routeContext, final RequestParameter<?> parameter) throws Exception {
if(routeContext.getRequest().getHeader(parameter.getName()) != null){
return Optional.fromNullable(createInstance(parameter.getType(), routeContext.getRequest().getHeader(parameter.getName())));
}
return Optional.absent();
}
private static Optional<?> extractCookieParam(final RouteContext routeContext, final RequestParameter<?> parameter) throws Exception {
final Cookie[] cookies = routeContext.getRequest().getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(parameter.getName())) {
return Optional.fromNullable(createInstance(parameter.getType(), cookie.getValue()));
}
}
}
return Optional.absent();
}
private static Optional<?> extractParam(final RouteContext routeContext, final RequestParameter<?> parameter) throws Exception {
final String[] values = routeContext.getRequest().getParameterMap().get(parameter.getName());
if (values != null) {
if (values.length == 1) {
return Optional.of(createInstance(parameter.getType(), values[0]));
} else {
throw LoggerMessages.MESSAGES.multivaluedParamsUnsupported(parameter.getName());
}
}
return Optional.absent();
}
private static Object createInstance( Class<?> type, String arg) throws Exception {
Constructor constructor = type.getDeclaredConstructor(String.class);
return constructor.newInstance(arg);
}
}