Search in sources :

Example 1 with JsonSchema

use of com.google.api.services.discovery.model.JsonSchema in project java-docs-samples by GoogleCloudPlatform.

the class OnlinePredictionSample method main.

public static void main(String[] args) throws Exception {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build();
    RestDescription api = discovery.apis().getRest("ml", "v1").execute();
    RestMethod method = api.getResources().get("projects").getMethods().get("predict");
    JsonSchema param = new JsonSchema();
    String projectId = "YOUR_PROJECT_ID";
    // You should have already deployed a model and a version.
    // For reference, see https://cloud.google.com/ml-engine/docs/deploying-models.
    String modelId = "YOUR_MODEL_ID";
    String versionId = "YOUR_VERSION_ID";
    param.set("name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId));
    GenericUrl url = new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true));
    System.out.println(url);
    String contentType = "application/json";
    File requestBodyFile = new File("input.txt");
    HttpContent content = new FileContent(contentType, requestBodyFile);
    System.out.println(content.getLength());
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content);
    String response = request.execute().parseAsString();
    System.out.println(response);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonSchema(com.google.api.services.discovery.model.JsonSchema) JsonFactory(com.google.api.client.json.JsonFactory) Discovery(com.google.api.services.discovery.Discovery) RestDescription(com.google.api.services.discovery.model.RestDescription) GenericUrl(com.google.api.client.http.GenericUrl) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) FileContent(com.google.api.client.http.FileContent) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) File(java.io.File) HttpContent(com.google.api.client.http.HttpContent) RestMethod(com.google.api.services.discovery.model.RestMethod)

Example 2 with JsonSchema

use of com.google.api.services.discovery.model.JsonSchema in project endpoints-java by cloudendpoints.

the class DiscoveryGenerator method convertToDiscoverySchema.

private JsonSchema convertToDiscoverySchema(Schema schema) {
    JsonSchema docSchema = new JsonSchema().setId(schema.name()).setType(schema.type());
    if (!schema.fields().isEmpty()) {
        Map<String, JsonSchema> fields = Maps.newLinkedHashMap();
        for (Field f : schema.fields().values()) {
            fields.put(f.name(), convertToDiscoverySchema(f));
        }
        docSchema.setProperties(fields);
    }
    docSchema.setDescription(schema.description());
    if (!schema.enumValues().isEmpty()) {
        docSchema.setEnum(new ArrayList<>(schema.enumValues()));
        docSchema.setEnumDescriptions(new ArrayList<>(schema.enumDescriptions()));
    }
    return docSchema;
}
Also used : Field(com.google.api.server.spi.config.model.Schema.Field) JsonSchema(com.google.api.services.discovery.model.JsonSchema)

Example 3 with JsonSchema

use of com.google.api.services.discovery.model.JsonSchema 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 4 with JsonSchema

use of com.google.api.services.discovery.model.JsonSchema in project endpoints-java by cloudendpoints.

the class DiscoveryGenerator method createStandardParameters.

private static Map<String, JsonSchema> createStandardParameters() {
    TreeMap<String, JsonSchema> params = new TreeMap<>();
    params.put(StandardParameters.ALT, new JsonSchema().setDefault("json").setDescription("Data format for the response.").setEnum(Lists.newArrayList("json")).setEnumDescriptions(Lists.newArrayList("Responses with Content-Type of application/json")).setLocation("query").setType("string"));
    params.put(StandardParameters.FIELDS, new JsonSchema().setDescription("Selector specifying which fields to include in a partial response.").setLocation("query").setType("string"));
    params.put(StandardParameters.KEY, new JsonSchema().setDescription("API key. Your API key identifies your project and provides you with " + "API access, quota, and reports. Required unless you provide an OAuth 2.0 " + "token.").setLocation("query").setType("string"));
    params.put(StandardParameters.OAUTH_TOKEN, new JsonSchema().setDescription("OAuth 2.0 token for the current user.").setLocation("query").setType("string"));
    params.put(StandardParameters.PRETTY_PRINT, new JsonSchema().setDefault("true").setDescription("Returns response with indentations and line breaks.").setLocation("query").setType("boolean"));
    params.put(StandardParameters.QUOTA_USER, new JsonSchema().setDescription("Available to use for quota purposes for server-side applications. " + "Can be any arbitrary string assigned to a user, but should not exceed 40 " + "characters. Overrides userIp if both are provided.").setLocation("query").setType("string"));
    params.put(StandardParameters.USER_IP, new JsonSchema().setDescription("IP address of the site where the request originates. Use this if " + "you want to enforce per-user limits.").setLocation("query").setType("string"));
    return params;
}
Also used : JsonSchema(com.google.api.services.discovery.model.JsonSchema) TreeMap(java.util.TreeMap)

Example 5 with JsonSchema

use of com.google.api.services.discovery.model.JsonSchema in project endpoints-java by cloudendpoints.

the class DiscoveryGenerator method writeApi.

private RestDescription writeApi(ApiKey apiKey, Iterable<ApiConfig> apiConfigs, DiscoveryContext context, SchemaRepository repo) {
    // 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());
    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());
        }
        for (ApiMethodConfig methodConfig : config.getApiClassConfig().getMethods().values()) {
            if (!methodConfig.isIgnored()) {
                writeApiMethod(config, servicePath, doc, methodConfig, repo);
            }
        }
    }
    List<Schema> schemas = repo.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 : ApiMethodConfig(com.google.api.server.spi.config.model.ApiMethodConfig) 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)

Aggregations

JsonSchema (com.google.api.services.discovery.model.JsonSchema)7 RestDescription (com.google.api.services.discovery.model.RestDescription)3 ApiParameterConfig (com.google.api.server.spi.config.model.ApiParameterConfig)2 Schema (com.google.api.server.spi.config.model.Schema)2 RestMethod (com.google.api.services.discovery.model.RestMethod)2 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)1 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)1 FileContent (com.google.api.client.http.FileContent)1 GenericUrl (com.google.api.client.http.GenericUrl)1 HttpContent (com.google.api.client.http.HttpContent)1 HttpRequest (com.google.api.client.http.HttpRequest)1 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)1 HttpTransport (com.google.api.client.http.HttpTransport)1 JsonFactory (com.google.api.client.json.JsonFactory)1 Description (com.google.api.server.spi.config.Description)1 ApiConfig (com.google.api.server.spi.config.model.ApiConfig)1 ApiMethodConfig (com.google.api.server.spi.config.model.ApiMethodConfig)1 ApiNamespaceConfig (com.google.api.server.spi.config.model.ApiNamespaceConfig)1 Field (com.google.api.server.spi.config.model.Schema.Field)1 Discovery (com.google.api.services.discovery.Discovery)1