Search in sources :

Example 6 with ApiParameterConfig

use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.

the class ApiConfigAnnotationReaderTest method genericParameterTypeTestImpl.

private <T> void genericParameterTypeTestImpl() throws Exception {
    @Api
    class Bar<T1> {

        @SuppressWarnings("unused")
        public void bar(T1 t1) {
        }
    }
    class Foo extends Bar<T> {
    }
    ApiConfig config = createConfig(Foo.class);
    annotationReader.loadEndpointMethods(serviceContext, Foo.class, config.getApiClassConfig().getMethods());
    ApiParameterConfig parameter = config.getApiClassConfig().getMethods().get(methodToEndpointMethod(Foo.class.getSuperclass().getDeclaredMethod("bar", Object.class))).getParameterConfigs().get(0);
    assertEquals(ApiParameterConfig.Classification.UNKNOWN, parameter.getClassification());
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) Foo(com.google.api.server.spi.testing.Foo) ApiConfig(com.google.api.server.spi.config.model.ApiConfig) SimpleLevelOverridingApi(com.google.api.server.spi.testing.SimpleLevelOverridingApi) SimpleLevelOverridingInheritedApi(com.google.api.server.spi.testing.SimpleLevelOverridingInheritedApi) Api(com.google.api.server.spi.config.Api)

Example 7 with ApiParameterConfig

use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.

the class ApiConfigAnnotationReaderTest method testParameterAnnotations_javax.

@Test
public void testParameterAnnotations_javax() throws Exception {
    @Api
    class Endpoint {

        @SuppressWarnings("unused")
        public void method(@javax.inject.Named("foo") @javax.annotation.Nullable int foo) {
        }
    }
    ApiConfig config = createConfig(Endpoint.class);
    annotationReader.loadEndpointClass(serviceContext, Endpoint.class, config);
    annotationReader.loadEndpointMethods(serviceContext, Endpoint.class, config.getApiClassConfig().getMethods());
    ApiMethodConfig methodConfig = Iterables.getOnlyElement(config.getApiClassConfig().getMethods().values());
    ApiParameterConfig parameterConfig = Iterables.getOnlyElement(methodConfig.getParameterConfigs());
    validateParameter(parameterConfig, "foo", true, null, int.class, null, int.class);
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) ApiConfig(com.google.api.server.spi.config.model.ApiConfig) SimpleLevelOverridingApi(com.google.api.server.spi.testing.SimpleLevelOverridingApi) SimpleLevelOverridingInheritedApi(com.google.api.server.spi.testing.SimpleLevelOverridingInheritedApi) Api(com.google.api.server.spi.config.Api) Test(org.junit.Test)

Example 8 with ApiParameterConfig

use of com.google.api.server.spi.config.model.ApiParameterConfig 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();
        JsonNode node;
        // this case, each part represents a named parameter instead.
        if (ServletFileUpload.isMultipartContent(servletRequest)) {
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(servletRequest);
                ObjectNode obj = (ObjectNode) objectReader.createObjectNode();
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        obj.put(item.getFieldName(), IoUtil.readStream(item.openStream()));
                    } else {
                        throw new BadRequestException("unable to parse multipart form field");
                    }
                }
                node = obj;
            } catch (FileUploadException e) {
                throw new BadRequestException("unable to parse multipart request", e);
            }
        } else {
            String requestBody = IoUtil.readRequestBody(servletRequest);
            logger.atFine().log("requestBody=%s", 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.
            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) {
        logger.atInfo().withCause(e).log("Unable to read request parameter(s)");
        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) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) EndpointMethod(com.google.api.server.spi.EndpointMethod) BadRequestException(com.google.api.server.spi.response.BadRequestException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 9 with ApiParameterConfig

use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.

the class SwaggerGenerator method writeApiMethod.

private void writeApiMethod(ApiMethodConfig methodConfig, ApiConfig apiConfig, Swagger swagger, GenerationContext genCtx) throws ApiConfigException {
    Path path = getOrCreatePath(swagger, methodConfig);
    Operation operation = new Operation();
    operation.setOperationId(getOperationId(apiConfig, methodConfig));
    operation.setDescription(methodConfig.getDescription());
    Collection<String> pathParameters = methodConfig.getPathParameters();
    for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
        switch(parameterConfig.getClassification()) {
            case API_PARAMETER:
                boolean isPathParameter = pathParameters.contains(parameterConfig.getName());
                SerializableParameter parameter = isPathParameter ? new PathParameter() : new QueryParameter();
                parameter.setName(parameterConfig.getName());
                parameter.setDescription(parameterConfig.getDescription());
                boolean required = isPathParameter || (!parameterConfig.getNullable() && parameterConfig.getDefaultValue() == null);
                if (parameterConfig.isRepeated()) {
                    TypeToken<?> t = parameterConfig.getRepeatedItemSerializedType();
                    parameter.setType("array");
                    Property p = getSwaggerArrayProperty(t);
                    if (parameterConfig.isEnum()) {
                        // TODO: Not sure if this is the right check
                        ((StringProperty) p).setEnum(getEnumValues(t));
                    }
                    parameter.setItems(p);
                } else if (parameterConfig.isEnum()) {
                    parameter.setType("string");
                    parameter.setEnum(getEnumValues(parameterConfig.getType()));
                    parameter.setRequired(required);
                } else {
                    parameter.setType(TYPE_TO_STRING_MAP.get(parameterConfig.getSchemaBaseType().getType()));
                    parameter.setFormat(TYPE_TO_FORMAT_MAP.get(parameterConfig.getSchemaBaseType().getType()));
                    parameter.setRequired(required);
                }
                operation.parameter(parameter);
                break;
            case RESOURCE:
                TypeToken<?> requestType = parameterConfig.getSchemaBaseType();
                Schema schema = genCtx.schemata.getOrAdd(requestType, apiConfig);
                BodyParameter bodyParameter = new BodyParameter();
                bodyParameter.setName("body");
                bodyParameter.setSchema(new RefModel(schema.name()));
                operation.addParameter(bodyParameter);
                break;
            case UNKNOWN:
                throw new IllegalArgumentException("Unclassifiable parameter type found.");
            case INJECTED:
                // Do nothing, these are synthetic and created by the framework.
                break;
        }
    }
    Response response = new Response().description("A successful response");
    if (methodConfig.hasResourceInResponse()) {
        TypeToken<?> returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), apiConfig);
        Schema schema = genCtx.schemata.getOrAdd(returnType, apiConfig);
        response.setSchema(new RefProperty(schema.name()));
    }
    operation.response(200, response);
    writeAuthConfig(swagger, methodConfig, operation);
    if (methodConfig.isApiKeyRequired()) {
        List<Map<String, List<String>>> security = operation.getSecurity();
        // security requirements, add a new one for just the API key.
        if (security != null) {
            for (Map<String, List<String>> securityEntry : security) {
                securityEntry.put(API_KEY, ImmutableList.<String>of());
            }
        } else {
            operation.addSecurity(API_KEY, ImmutableList.<String>of());
        }
        Map<String, SecuritySchemeDefinition> definitions = swagger.getSecurityDefinitions();
        if (definitions == null || !definitions.containsKey(API_KEY)) {
            swagger.securityDefinition(API_KEY, new ApiKeyAuthDefinition(API_KEY_PARAM, In.QUERY));
        }
    }
    path.set(methodConfig.getHttpMethod().toLowerCase(), operation);
    addDefinedMetricCosts(genCtx.limitMetrics, operation, methodConfig.getMetricCosts());
}
Also used : SerializableParameter(io.swagger.models.parameters.SerializableParameter) QueryParameter(io.swagger.models.parameters.QueryParameter) RefModel(io.swagger.models.RefModel) Schema(com.google.api.server.spi.config.model.Schema) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) RefProperty(io.swagger.models.properties.RefProperty) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) LongProperty(io.swagger.models.properties.LongProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) DateTimeProperty(io.swagger.models.properties.DateTimeProperty) ByteArrayProperty(io.swagger.models.properties.ByteArrayProperty) RefProperty(io.swagger.models.properties.RefProperty) FloatProperty(io.swagger.models.properties.FloatProperty) DateProperty(io.swagger.models.properties.DateProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) Path(io.swagger.models.Path) ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Response(io.swagger.models.Response) ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 10 with ApiParameterConfig

use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.

the class DiscoveryGenerator method computeParameterOrder.

private List<String> computeParameterOrder(ApiMethodConfig methodConfig) {
    ImmutableSortedSet.Builder<String> queryParamBuilder = ImmutableSortedSet.naturalOrder();
    Collection<String> pathParameters = methodConfig.getPathParameters();
    for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
        if (parameterConfig.getClassification() == Classification.API_PARAMETER && !pathParameters.contains(parameterConfig.getName()) && !parameterConfig.getNullable()) {
            queryParamBuilder.add(parameterConfig.getName());
        }
    }
    List<String> order = new ArrayList<>(pathParameters);
    order.addAll(queryParamBuilder.build());
    return order;
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) ArrayList(java.util.ArrayList)

Aggregations

ApiParameterConfig (com.google.api.server.spi.config.model.ApiParameterConfig)17 Api (com.google.api.server.spi.config.Api)7 ApiConfig (com.google.api.server.spi.config.model.ApiConfig)7 SimpleLevelOverridingApi (com.google.api.server.spi.testing.SimpleLevelOverridingApi)7 SimpleLevelOverridingInheritedApi (com.google.api.server.spi.testing.SimpleLevelOverridingInheritedApi)7 Test (org.junit.Test)6 ApiMethodConfig (com.google.api.server.spi.config.model.ApiMethodConfig)4 Schema (com.google.api.server.spi.config.model.Schema)4 JsonSchema (com.google.api.services.discovery.model.JsonSchema)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 EndpointMethod (com.google.api.server.spi.EndpointMethod)2 Foo (com.google.api.server.spi.testing.Foo)2 RestMethod (com.google.api.services.discovery.model.RestMethod)2 Request (com.google.api.services.discovery.model.RestMethod.Request)2 Response (com.google.api.services.discovery.model.RestMethod.Response)2 ArrayList (java.util.ArrayList)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 DefaultValue (com.google.api.server.spi.config.DefaultValue)1 Description (com.google.api.server.spi.config.Description)1