Search in sources :

Example 1 with EndpointMethod

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);
    }
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpServletRequest(javax.servlet.http.HttpServletRequest) EndpointMethod(com.google.api.server.spi.EndpointMethod) BadRequestException(com.google.api.server.spi.response.BadRequestException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 2 with EndpointMethod

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;
}
Also used : User(com.google.api.server.spi.auth.common.User) JsonNode(com.fasterxml.jackson.databind.JsonNode) ParameterizedType(java.lang.reflect.ParameterizedType) TypeToken(com.google.common.reflect.TypeToken) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) EndpointMethod(com.google.api.server.spi.EndpointMethod) ServletContext(javax.servlet.ServletContext) Collection(java.util.Collection)

Example 3 with EndpointMethod

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;
}
Also used : Method(java.lang.reflect.Method) EndpointMethod(com.google.api.server.spi.EndpointMethod) Annotation(java.lang.annotation.Annotation)

Example 4 with EndpointMethod

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");
}
Also used : ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) EndpointMethod(com.google.api.server.spi.EndpointMethod) Test(org.junit.Test)

Example 5 with EndpointMethod

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);
}
Also used : ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) EndpointMethod(com.google.api.server.spi.EndpointMethod) ArrayEndpoint(com.google.api.server.spi.testing.ArrayEndpoint) Test(org.junit.Test)

Aggregations

EndpointMethod (com.google.api.server.spi.EndpointMethod)26 ApiMethodConfig (com.google.api.server.spi.config.model.ApiMethodConfig)14 Test (org.junit.Test)14 Method (java.lang.reflect.Method)6 Annotation (java.lang.annotation.Annotation)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 Named (com.google.api.server.spi.config.Named)2 ApiParameterConfig (com.google.api.server.spi.config.model.ApiParameterConfig)2 TypeToken (com.google.common.reflect.TypeToken)2 Map (java.util.Map)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 MethodHierarchyReader (com.google.api.server.spi.MethodHierarchyReader)1 TypeLoader (com.google.api.server.spi.TypeLoader)1 EndpointsAuthenticator (com.google.api.server.spi.auth.EndpointsAuthenticator)1 EndpointsPeerAuthenticator (com.google.api.server.spi.auth.EndpointsPeerAuthenticator)1 User (com.google.api.server.spi.auth.common.User)1 Authenticator (com.google.api.server.spi.config.Authenticator)1 PeerAuthenticator (com.google.api.server.spi.config.PeerAuthenticator)1 ApiSerializationConfig (com.google.api.server.spi.config.model.ApiSerializationConfig)1