use of com.google.api.server.spi.EndpointMethod in project endpoints-java by cloudendpoints.
the class RestServletRequestParamReader method read.
@Override
public Object[] read() throws ServiceException {
// TODO: Take charset from content-type as encoding
try {
EndpointMethod method = getMethod();
if (method.getParameterClasses().length == 0) {
return new Object[0];
}
HttpServletRequest servletRequest = endpointsContext.getRequest();
String requestBody = IoUtil.readRequestBody(servletRequest);
logger.log(Level.FINE, "requestBody=" + requestBody);
// Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to
// path and query parameters being injected into the body), bodies are optional here, so we
// create an empty body and inject named parameters to make deserialize work.
JsonNode node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() : objectReader.readTree(requestBody);
if (!node.isObject()) {
throw new BadRequestException("expected a JSON object body");
}
ObjectNode body = (ObjectNode) node;
Map<String, Class<?>> parameterMap = getParameterMap(method);
// the order of precedence is resource field > query parameter > path parameter.
for (Enumeration<?> e = servletRequest.getParameterNames(); e.hasMoreElements(); ) {
String parameterName = (String) e.nextElement();
if (!body.has(parameterName)) {
Class<?> parameterClass = parameterMap.get(parameterName);
ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName);
if (parameterClass != null && parameterConfig.isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : servletRequest.getParameterValues(parameterName)) {
values.add(value);
}
} else {
body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]);
}
}
}
for (Entry<String, String> entry : rawPathParameters.entrySet()) {
String parameterName = entry.getKey();
Class<?> parameterClass = parameterMap.get(parameterName);
if (parameterClass != null && !body.has(parameterName)) {
if (parameterConfigMap.get(parameterName).isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) {
values.add(value);
}
} else {
body.put(parameterName, entry.getValue());
}
}
}
for (Entry<String, ApiParameterConfig> entry : parameterConfigMap.entrySet()) {
if (!body.has(entry.getKey()) && entry.getValue().getDefaultValue() != null) {
body.put(entry.getKey(), entry.getValue().getDefaultValue());
}
}
return deserializeParams(body);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
e.printStackTrace();
throw new BadRequestException(e);
}
}
use of com.google.api.server.spi.EndpointMethod in project endpoints-java by cloudendpoints.
the class ServletRequestParamReader method deserializeParams.
protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ServiceException {
EndpointMethod method = getMethod();
Class<?>[] paramClasses = method.getParameterClasses();
TypeToken<?>[] paramTypes = method.getParameterTypes();
Object[] params = new Object[paramClasses.length];
List<String> parameterNames = getParameterNames(method);
for (int i = 0; i < paramClasses.length; i++) {
TypeToken<?> type = paramTypes[i];
Class<?> clazz = paramClasses[i];
if (User.class.isAssignableFrom(clazz)) {
// User type parameter requires no Named annotation (ignored if present)
User user = getUser();
if (user == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
throw new UnauthorizedException("Valid user credentials are required.");
}
if (user == null || clazz.isAssignableFrom(user.getClass())) {
params[i] = user;
logger.log(Level.FINE, "deserialize: User injected into param[{0}]", i);
} else {
logger.log(Level.WARNING, "deserialize: User object of type {0} is not assignable to {1}. User will be null.", new Object[] { user.getClass().getName(), clazz.getName() });
}
} else if (APPENGINE_USER_CLASS_NAME.equals(clazz.getName())) {
// User type parameter requires no Named annotation (ignored if present)
com.google.appengine.api.users.User appEngineUser = getAppEngineUser();
if (appEngineUser == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
throw new UnauthorizedException("Valid user credentials are required.");
}
params[i] = appEngineUser;
logger.log(Level.FINE, "deserialize: App Engine User injected into param[{0}]", i);
} else if (clazz == HttpServletRequest.class) {
// HttpServletRequest type parameter requires no Named annotation (ignored if present)
params[i] = endpointsContext.getRequest();
logger.log(Level.FINE, "deserialize: HttpServletRequest injected into param[{0}]", i);
} else if (clazz == ServletContext.class) {
// ServletContext type parameter requires no Named annotation (ignored if present)
params[i] = servletContext;
logger.log(Level.FINE, "deserialize: ServletContext {0} injected into param[{1}]", new Object[] { params[i], i });
} else {
String name = parameterNames.get(i);
if (Strings.isNullOrEmpty(name)) {
params[i] = (node == null) ? null : objectReader.forType(clazz).readValue(node);
logger.log(Level.FINE, "deserialize: {0} {1} injected into unnamed param[{2}]", new Object[] { clazz, params[i], i });
} else if (StandardParameters.isStandardParamName(name)) {
params[i] = getStandardParamValue(node, name);
} else {
JsonNode nodeValue = node.get(name);
if (nodeValue == null) {
params[i] = null;
} else {
// Check for collection type
if (Collection.class.isAssignableFrom(clazz) && type.getType() instanceof ParameterizedType) {
params[i] = deserializeCollection(clazz, (ParameterizedType) type.getType(), nodeValue);
} else {
params[i] = objectReader.forType(clazz).readValue(nodeValue);
}
}
logger.log(Level.FINE, "deserialize: {0} {1} injected into param[{2}] named {3}", new Object[] { clazz, params[i], i, name });
}
}
}
return params;
}
use of com.google.api.server.spi.EndpointMethod in project endpoints-java by cloudendpoints.
the class ServletRequestParamReader method getParameterNames.
protected static List<String> getParameterNames(EndpointMethod endpointMethod) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
List<String> parameterNames = endpointMethod.getParameterNames();
if (parameterNames == null) {
Method method = endpointMethod.getMethod();
parameterNames = new ArrayList<>();
for (int parameter = 0; parameter < method.getParameterTypes().length; parameter++) {
Annotation annotation = AnnotationUtil.getNamedParameter(method, parameter, Named.class);
if (annotation == null) {
parameterNames.add(null);
} else {
parameterNames.add((String) annotation.getClass().getMethod("value").invoke(annotation));
}
}
endpointMethod.setParameterNames(parameterNames);
}
return parameterNames;
}
use of com.google.api.server.spi.EndpointMethod in project endpoints-java by cloudendpoints.
the class EndpointsMethodHandlerTest method rootMethodHandler.
@Test
public void rootMethodHandler() throws Exception {
EndpointMethod method = systemService.resolveService("TestEndpoint", "root");
ApiMethodConfig methodConfig = new ApiMethodConfig(method, typeLoader, apiConfig.getApiClassConfig());
methodConfig.setPath("/root");
TestMethodHandler handler = new TestMethodHandler(ServletInitializationParameters.builder().build(), method, apiConfig, methodConfig, systemService, 200);
assertThat(handler.getRestPath()).isEqualTo("root");
}
use of com.google.api.server.spi.EndpointMethod in project endpoints-java by cloudendpoints.
the class EndpointsMethodHandlerTest method fail_findService.
@Test
public void fail_findService() throws Exception {
EndpointMethod method = systemService.resolveService("TestEndpoint", "simple");
ApiMethodConfig methodConfig = new ApiMethodConfig(method, typeLoader, apiConfig.getApiClassConfig());
systemService = SystemService.builder().withDefaults(classLoader).addService(ArrayEndpoint.class, new ArrayEndpoint()).build();
TestMethodHandler handler = new TestMethodHandler(ServletInitializationParameters.builder().build(), method, apiConfig, methodConfig, systemService, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RESOURCE);
handler.getRestHandler().handle(context);
}
Aggregations