Search in sources :

Example 1 with Schema

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

the class DiscoveryGenerator method writeApiMethod.

private void writeApiMethod(ApiConfig config, String servicePath, RestDescription doc, ApiMethodConfig methodConfig, SchemaRepository repo) {
    List<String> parts = DOT_SPLITTER.splitToList(methodConfig.getFullMethodName());
    Map<String, RestMethod> methods = getMethodMapFromDoc(doc, parts);
    Map<String, JsonSchema> parameters = convertMethodParameters(methodConfig);
    RestMethod method = new RestMethod().setDescription(methodConfig.getDescription()).setHttpMethod(methodConfig.getHttpMethod()).setId(methodConfig.getFullMethodName()).setPath(methodConfig.getCanonicalPath().substring(servicePath.length())).setScopes(AuthScopeExpressions.encodeMutable(methodConfig.getScopeExpression()));
    List<String> parameterOrder = computeParameterOrder(methodConfig);
    if (!parameterOrder.isEmpty()) {
        method.setParameterOrder(parameterOrder);
    }
    if (!parameters.isEmpty()) {
        method.setParameters(parameters);
    }
    ApiParameterConfig requestParamConfig = getAndCheckMethodRequestResource(methodConfig);
    if (requestParamConfig != null) {
        TypeToken<?> requestType = requestParamConfig.getSchemaBaseType();
        Schema schema = repo.getOrAdd(requestType, config);
        method.setRequest(new Request().set$ref(schema.name()).setParameterName("resource"));
    }
    if (methodConfig.hasResourceInResponse()) {
        TypeToken<?> returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), config);
        Schema schema = repo.getOrAdd(returnType, config);
        method.setResponse(new Response().set$ref(schema.name()));
    }
    methods.put(parts.get(parts.size() - 1), method);
}
Also used : Response(com.google.api.services.discovery.model.RestMethod.Response) ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) JsonSchema(com.google.api.services.discovery.model.JsonSchema) Schema(com.google.api.server.spi.config.model.Schema) JsonSchema(com.google.api.services.discovery.model.JsonSchema) Request(com.google.api.services.discovery.model.RestMethod.Request) RestMethod(com.google.api.services.discovery.model.RestMethod)

Example 2 with Schema

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

the class DiscoveryGenerator method writeApiMethod.

private void writeApiMethod(ApiConfig config, String servicePath, RestDescription doc, ApiMethodConfig methodConfig, SchemaRepository schemaRepo, AuthScopeRepository scopeRepo) {
    List<String> parts = DOT_SPLITTER.splitToList(methodConfig.getFullMethodName());
    Map<String, RestMethod> methods = getMethodMapFromDoc(doc, parts);
    Map<String, JsonSchema> parameters = convertMethodParameters(methodConfig);
    AuthScopeExpression scopeExpression = methodConfig.getScopeExpression();
    RestMethod method = new RestMethod().setDescription(methodConfig.getDescription()).setHttpMethod(methodConfig.getHttpMethod()).setId(methodConfig.getFullMethodName()).setPath(methodConfig.getCanonicalPath().substring(servicePath.length())).setScopes(AuthScopeExpressions.encodeMutable(scopeExpression));
    scopeRepo.add(scopeExpression);
    List<String> parameterOrder = computeParameterOrder(methodConfig);
    if (!parameterOrder.isEmpty()) {
        method.setParameterOrder(parameterOrder);
    }
    if (!parameters.isEmpty()) {
        method.setParameters(parameters);
    }
    ApiParameterConfig requestParamConfig = getAndCheckMethodRequestResource(methodConfig);
    if (requestParamConfig != null) {
        TypeToken<?> requestType = requestParamConfig.getSchemaBaseType();
        Schema schema = schemaRepo.getOrAdd(requestType, config);
        method.setRequest(new Request().set$ref(schema.name()).setParameterName("resource"));
    }
    if (methodConfig.hasResourceInResponse()) {
        TypeToken<?> returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), config);
        Schema schema = schemaRepo.getOrAdd(returnType, config);
        method.setResponse(new Response().set$ref(schema.name()));
    }
    methods.put(parts.get(parts.size() - 1), method);
}
Also used : Response(com.google.api.services.discovery.model.RestMethod.Response) ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) AuthScopeExpression(com.google.api.server.spi.config.scope.AuthScopeExpression) JsonSchema(com.google.api.services.discovery.model.JsonSchema) Schema(com.google.api.server.spi.config.model.Schema) JsonSchema(com.google.api.services.discovery.model.JsonSchema) Request(com.google.api.services.discovery.model.RestMethod.Request) RestMethod(com.google.api.services.discovery.model.RestMethod)

Example 3 with Schema

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

the class SwaggerGenerator method writeApi.

private void writeApi(ApiKey apiKey, ImmutableList<? extends ApiConfig> apiConfigs, Swagger swagger, GenerationContext genCtx) throws ApiConfigException {
    // TODO: This may result in duplicate validations in the future if made available online
    genCtx.validator.validate(apiConfigs);
    for (ApiConfig apiConfig : apiConfigs) {
        for (ApiLimitMetricConfig limitMetric : apiConfig.getApiLimitMetrics()) {
            addNonConflictingApiLimitMetric(genCtx.limitMetrics, limitMetric);
        }
        writeApiClass(apiConfig, swagger, genCtx);
    }
    List<Schema> schemas = genCtx.schemata.getAllSchemaForApi(apiKey);
    for (Schema schema : schemas) {
        if (schema.enumValues().isEmpty()) {
            getOrCreateDefinitionMap(swagger).put(schema.name(), convertToSwaggerSchema(schema));
        }
    }
}
Also used : Schema(com.google.api.server.spi.config.model.Schema) ApiConfig(com.google.api.server.spi.config.model.ApiConfig) ApiLimitMetricConfig(com.google.api.server.spi.config.model.ApiLimitMetricConfig)

Example 4 with Schema

use of com.google.api.server.spi.config.model.Schema 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 5 with Schema

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

the class DiscoveryGenerator method writeApi.

private RestDescription writeApi(ApiKey apiKey, Iterable<ApiConfig> apiConfigs, DiscoveryContext context, SchemaRepository schemaRepo) {
    // The first step is to scan all methods and try to extract a base path, aka a common prefix
    // for all methods. This prefix must end in a slash and can't contain any path parameters.
    String servicePath = computeApiServicePath(apiConfigs);
    String basePath = context.basePath + "/" + servicePath;
    RestDescription doc = REST_SKELETON.clone().setBasePath(basePath).setBaseUrl(context.getApiRoot() + "/" + servicePath).setId(apiKey.getName() + ":" + apiKey.getVersion()).setName(apiKey.getName()).setRootUrl(context.getApiRoot() + "/").setServicePath(servicePath).setVersion(apiKey.getVersion());
    final AuthScopeRepository scopeRepo = new AuthScopeRepository();
    for (ApiConfig config : apiConfigs) {
        // precedence here if there happens to be divergence.
        if (config.getDescription() != null) {
            doc.setDescription(config.getDescription());
        }
        if (config.getTitle() != null) {
            doc.setTitle(config.getTitle());
        }
        if (config.getDocumentationLink() != null) {
            doc.setDocumentationLink(config.getDocumentationLink());
        }
        if (config.getNamespaceConfig() != null) {
            ApiNamespaceConfig namespaceConfig = config.getNamespaceConfig();
            if (!Strings.isEmptyOrWhitespace(namespaceConfig.getOwnerName())) {
                doc.setOwnerName(namespaceConfig.getOwnerName());
            }
            if (!Strings.isEmptyOrWhitespace(namespaceConfig.getOwnerDomain())) {
                doc.setOwnerDomain(namespaceConfig.getOwnerDomain());
            }
            if (!Strings.isEmptyOrWhitespace(namespaceConfig.getPackagePath())) {
                doc.setPackagePath(namespaceConfig.getPackagePath());
            }
        }
        if (config.getCanonicalName() != null) {
            doc.setCanonicalName(config.getCanonicalName());
        }
        scopeRepo.add(config.getScopeExpression());
        for (ApiMethodConfig methodConfig : config.getApiClassConfig().getMethods().values()) {
            if (!methodConfig.isIgnored()) {
                writeApiMethod(config, servicePath, doc, methodConfig, schemaRepo, scopeRepo);
            }
        }
    }
    Map<String, ScopesElement> scopeElements = new LinkedHashMap<>();
    for (Entry<String, String> entry : scopeRepo.getDescriptionsByScope().entrySet()) {
        scopeElements.put(entry.getKey(), new ScopesElement().setDescription(entry.getValue()));
    }
    doc.setAuth(new Auth().setOauth2(new Oauth2().setScopes(scopeElements)));
    List<Schema> schemas = schemaRepo.getAllSchemaForApi(apiKey);
    if (!schemas.isEmpty()) {
        Map<String, JsonSchema> docSchemas = Maps.newTreeMap();
        for (Schema schema : schemas) {
            docSchemas.put(schema.name(), convertToDiscoverySchema(schema));
        }
        doc.setSchemas(docSchemas);
    }
    return doc;
}
Also used : ScopesElement(com.google.api.services.discovery.model.RestDescription.Auth.Oauth2.ScopesElement) Oauth2(com.google.api.services.discovery.model.RestDescription.Auth.Oauth2) Schema(com.google.api.server.spi.config.model.Schema) JsonSchema(com.google.api.services.discovery.model.JsonSchema) JsonSchema(com.google.api.services.discovery.model.JsonSchema) RestDescription(com.google.api.services.discovery.model.RestDescription) ApiConfig(com.google.api.server.spi.config.model.ApiConfig) ApiNamespaceConfig(com.google.api.server.spi.config.model.ApiNamespaceConfig) LinkedHashMap(java.util.LinkedHashMap) ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) Auth(com.google.api.services.discovery.model.RestDescription.Auth) AuthScopeRepository(com.google.api.server.spi.config.model.AuthScopeRepository)

Aggregations

Schema (com.google.api.server.spi.config.model.Schema)6 ApiParameterConfig (com.google.api.server.spi.config.model.ApiParameterConfig)4 JsonSchema (com.google.api.services.discovery.model.JsonSchema)3 ApiConfig (com.google.api.server.spi.config.model.ApiConfig)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 LinkedHashMap (java.util.LinkedHashMap)2 ApiLimitMetricConfig (com.google.api.server.spi.config.model.ApiLimitMetricConfig)1 ApiMethodConfig (com.google.api.server.spi.config.model.ApiMethodConfig)1 ApiNamespaceConfig (com.google.api.server.spi.config.model.ApiNamespaceConfig)1 AuthScopeRepository (com.google.api.server.spi.config.model.AuthScopeRepository)1 AuthScopeExpression (com.google.api.server.spi.config.scope.AuthScopeExpression)1 RestDescription (com.google.api.services.discovery.model.RestDescription)1 Auth (com.google.api.services.discovery.model.RestDescription.Auth)1 Oauth2 (com.google.api.services.discovery.model.RestDescription.Auth.Oauth2)1 ScopesElement (com.google.api.services.discovery.model.RestDescription.Auth.Oauth2.ScopesElement)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Operation (io.swagger.models.Operation)1