Java Code Examples for io.swagger.v3.oas.models.OpenAPI#getInfo()

The following examples show how to use io.swagger.v3.oas.models.OpenAPI#getInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeScriptClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {

    if (additionalProperties.containsKey(NPM_NAME)) {

        // If no npmVersion is provided in additional properties, version from API specification is used.
        // If none of them is provided then fallbacks to default version
        if (additionalProperties.containsKey(NPM_VERSION)) {
            this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
        } else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
            this.setNpmVersion(openAPI.getInfo().getVersion());
        }

        if (additionalProperties.containsKey(SNAPSHOT) && Boolean.parseBoolean(additionalProperties.get(SNAPSHOT).toString())) {
            if (npmVersion.toUpperCase(Locale.ROOT).matches("^.*-SNAPSHOT$")) {
                this.setNpmVersion(npmVersion + "." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
            } else {
                this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
            }
        }
        additionalProperties.put(NPM_VERSION, npmVersion);

    }
}
 
Example 2
Source File: AbstractTypeScriptClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {

    if (additionalProperties.containsKey(NPM_NAME)) {

        // If no npmVersion is provided in additional properties, version from API specification is used.
        // If none of them is provided then fallbacks to default version
        if (additionalProperties.containsKey(NPM_VERSION)) {
            this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
        } else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
            this.setNpmVersion(openAPI.getInfo().getVersion());
        }

        if (additionalProperties.containsKey(SNAPSHOT) && Boolean.parseBoolean(additionalProperties.get(SNAPSHOT).toString())) {
            if (npmVersion.toUpperCase(Locale.ROOT).matches("^.*-SNAPSHOT$")) {
                this.setNpmVersion(npmVersion + "." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
            } else {
                this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
            }
        }
        additionalProperties.put(NPM_VERSION, npmVersion);

    }

}
 
Example 3
Source File: RustServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {

    Info info = openAPI.getInfo();

    URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
    additionalProperties.put("serverHost", url.getHost());
    additionalProperties.put("serverPort", URLPathUtils.getPort(url, serverPort));

    if (packageVersion == null || "".equals(packageVersion)) {
        List<String> versionComponents = new ArrayList<>(Arrays.asList(info.getVersion().split("[.]")));
        if (versionComponents.size() < 1) {
            versionComponents.add("1");
        }
        while (versionComponents.size() < 3) {
            versionComponents.add("0");
        }

        setPackageVersion(StringUtils.join(versionComponents, "."));
    }

    additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
}
 
Example 4
Source File: TaskGenerateOpenApiTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_UseDefaultProperties_when_applicationPropertiesIsEmpty()
        throws Exception {
    taskGenerateOpenApi = new TaskGenerateOpenApi(applicationPropertiesFile,
            javaSource,
            this.getClass().getClassLoader(),
            generatedOpenAPI);
    taskGenerateOpenApi.execute();

    OpenAPI generatedOpenAPI = getGeneratedOpenAPI();
    Info info = generatedOpenAPI.getInfo();
    Assert.assertEquals(
            "Generated OpenAPI should have default application title",
            OpenApiSpecGenerator.DEFAULT_APPLICATION_TITLE,
            info.getTitle());
    Assert.assertEquals(
            "Generated OpenAPI should have default "
                    + "application API version",
            OpenApiSpecGenerator.DEFAULT_APPLICATION_API_VERSION,
            info.getVersion());

    List<Server> servers = generatedOpenAPI.getServers();
    Assert.assertEquals("Generated OpenAPI should a default server", 1,
            servers.size());
    Assert.assertEquals("Generated OpenAPI should have default url server",
            OpenApiSpecGenerator.DEFAULT_SERVER
                    + OpenApiSpecGenerator.DEFAULT_PREFIX,
            servers.get(0).getUrl());

    Assert.assertEquals(
            "Generated OpenAPI should have default server description",
            OpenApiSpecGenerator.DEFAULT_SERVER_DESCRIPTION,
            servers.get(0).getDescription());
}
 
Example 5
Source File: BallerinaService.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Build a {@link BallerinaService} object from a {@link OpenAPI} object.
 * All non iterable objects using handlebars library is converted into
 * supported iterable object types.
 *
 * @param openAPI {@link OpenAPI} type object to be converted
 * @return Converted {@link BallerinaService} object
 */
@Override
public BallerinaService buildContext(OpenAPI openAPI) {
    this.info = openAPI.getInfo();
    this.tags = openAPI.getTags();
    this.containerConfig = CmdUtils.getContainerConfig();
    this.config = CmdUtils.getConfig();

    return this;
}
 
Example 6
Source File: JavascriptFlowtypedClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (StringUtils.isBlank(npmName) && info.getTitle() != null) {
            // when projectName is not specified, generate it from info.title
            npmName = sanitizeName(dashize(info.getTitle()));
        }
        if (StringUtils.isBlank(npmVersion)) {
            // when projectVersion is not specified, use info.version
            npmVersion = escapeUnsafeCharacters(escapeQuotationMark(info.getVersion()));
        }
    }

    // default values
    if (StringUtils.isBlank(npmName)) {
        npmName = "openapi-js-client";
    }
    if (StringUtils.isBlank(npmVersion)) {
        npmVersion = "1.0.0";
    }

    additionalProperties.put(NPM_NAME, npmName);
    additionalProperties.put(NPM_VERSION, npmVersion);
    additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
}
 
Example 7
Source File: CLibcurlClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        setProjectName((escapeText(info.getTitle())));
    } else {
        setProjectName(defaultProjectName);
    }
    additionalProperties.put(PROJECT_NAME, projectName);
}
 
Example 8
Source File: OpenAPISerializer.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(OpenAPI value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (value != null) {
        gen.writeStartObject();
        gen.writeStringField("openapi", value.getOpenapi());
        if(value.getInfo() != null) {
            gen.writeObjectField("info", value.getInfo());
        }
        if(value.getExternalDocs() != null) {
            gen.writeObjectField("externalDocs", value.getExternalDocs());
        }
        if(value.getServers() != null) {
            gen.writeObjectField("servers", value.getServers());
        }
        if(value.getSecurity() != null) {
            gen.writeObjectField("security", value.getSecurity());
        }
        if(value.getTags() != null) {
            gen.writeObjectField("tags", value.getTags());
        }
        if(value.getPaths() != null) {
            gen.writeObjectField("paths", value.getPaths());
        }
        if(value.getComponents() != null) {
            gen.writeObjectField("components", value.getComponents());
        }
        if(value.getExtensions() != null) {
            for (Entry<String, Object> e : value.getExtensions().entrySet()) {
                gen.writeObjectField(e.getKey(), e.getValue());
            }
        }
        gen.writeEndObject();
    }
}
 
Example 9
Source File: ElixirClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    Info info = openAPI.getInfo();
    if (moduleName == null) {
        if (info.getTitle() != null) {
            // default to the appName (from title field)
            setModuleName(modulized(escapeText(info.getTitle())));
        } else {
            setModuleName(defaultModuleName);
        }
    }
    additionalProperties.put("moduleName", moduleName);

    if (!additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
        additionalProperties.put(CodegenConstants.PACKAGE_NAME, underscored(moduleName));
    }

    supportingFiles.add(new SupportingFile("connection.ex.mustache",
            sourceFolder(),
            "connection.ex"));

    supportingFiles.add(new SupportingFile("request_builder.ex.mustache",
            sourceFolder(),
            "request_builder.ex"));


    supportingFiles.add(new SupportingFile("deserializer.ex.mustache",
            sourceFolder(),
            "deserializer.ex"));
}
 
Example 10
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "data")
public void readInfoObject(JsonNode rootNode) throws Exception {


    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    Assert.assertEquals(openAPI.getOpenapi(),"3.0.1");


    final Info info = openAPI.getInfo();
    Assert.assertNotNull(info);
    Assert.assertEquals(info.getTitle(), "Sample Pet Store App");
    Assert.assertEquals(info.getDescription(), "This is a sample server Petstore");
    Assert.assertEquals(info.getTermsOfService(), "http://swagger.io/terms/");
    Assert.assertNotNull(info.getExtensions().get("x-info"));
    Assert.assertEquals(info.getExtensions().get("x-info").toString(),"info extension");

    final Contact contact = info.getContact();
    Assert.assertNotNull(contact);
    Assert.assertEquals(contact.getName(),"API Support");
    Assert.assertEquals(contact.getUrl(),"http://www.example.com/support");
    Assert.assertEquals(contact.getEmail(),"[email protected]");
    Assert.assertNotNull(contact.getExtensions().get("x-contact"));
    Assert.assertEquals(contact.getExtensions().get("x-contact").toString(),"contact extension");

    final License license = info.getLicense();
    Assert.assertNotNull(license);
    Assert.assertEquals(license.getName(), "Apache 2.0");
    Assert.assertEquals(license.getUrl(), "http://www.apache.org/licenses/LICENSE-2.0.html");
    Assert.assertNotNull(license.getExtensions());

    Assert.assertEquals(info.getVersion(), "1.0.1");

}
 
Example 11
Source File: StaticHtml2Generator.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Parse Markdown to HTML for the main "Description" attribute
 *
 * @param openAPI The base object containing the global description through "Info" class
 */
private void preparHtmlForGlobalDescription(OpenAPI openAPI) {
    if (openAPI.getInfo() == null) {
        return;
    }

    String currentDescription = openAPI.getInfo().getDescription();
    if (currentDescription != null && !currentDescription.isEmpty()) {
        Markdown markInstance = new Markdown();
        openAPI.getInfo().setDescription(markInstance.toHtml(currentDescription));
    } else {
        LOGGER.error("OpenAPI object description is empty [" + openAPI.getInfo().getTitle() + "]");
    }
}
 
Example 12
Source File: JavascriptClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (StringUtils.isBlank(projectName) && info.getTitle() != null) {
            // when projectName is not specified, generate it from info.title
            projectName = sanitizeName(dashize(info.getTitle()));
        }
        if (StringUtils.isBlank(projectVersion)) {
            // when projectVersion is not specified, use info.version
            projectVersion = escapeUnsafeCharacters(escapeQuotationMark(info.getVersion()));
        }
        if (projectDescription == null) {
            // when projectDescription is not specified, use info.description
            if (StringUtils.isEmpty(info.getDescription())) {
                projectDescription = "JS API client generated by OpenAPI Generator";
            } else {
                projectDescription = sanitizeName(info.getDescription());
            }
        }

        // when licenceName is not specified, use info.license
        if (additionalProperties.get(CodegenConstants.LICENSE_NAME) == null && info.getLicense() != null) {
            License license = info.getLicense();
            licenseName = license.getName();
        }
    }

    // default values
    if (StringUtils.isBlank(projectName)) {
        projectName = "openapi-js-client";
    }
    if (StringUtils.isBlank(moduleName)) {
        moduleName = camelize(underscore(projectName));
    }
    if (StringUtils.isBlank(projectVersion)) {
        projectVersion = "1.0.0";
    }
    if (projectDescription == null) {
        projectDescription = "Client library of " + projectName;
    }
    if (StringUtils.isBlank(licenseName)) {
        licenseName = "Unlicense";
    }

    additionalProperties.put(PROJECT_NAME, projectName);
    additionalProperties.put(MODULE_NAME, moduleName);
    additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
    additionalProperties.put(PROJECT_VERSION, projectVersion);
    additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName);
    additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
    additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
    additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
    additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
    additionalProperties.put(USE_PROMISES, usePromises);
    additionalProperties.put(USE_INHERITANCE, supportsInheritance);
    additionalProperties.put(EMIT_MODEL_METHODS, emitModelMethods);
    additionalProperties.put(EMIT_JS_DOC, emitJSDoc);
    additionalProperties.put(USE_ES6, useES6);
    additionalProperties.put(NPM_REPOSITORY, npmRepository);

    // make api and model doc path available in mustache template
    additionalProperties.put("apiDocPath", apiDocPath);
    additionalProperties.put("modelDocPath", modelDocPath);

    String[][] supportingTemplateFiles = JAVASCRIPT_SUPPORTING_FILES;
    if (useES6) {
        supportingTemplateFiles = JAVASCRIPT_ES6_SUPPORTING_FILES;
    }

    for (String[] supportingTemplateFile : supportingTemplateFiles) {
        supportingFiles.add(new SupportingFile(supportingTemplateFile[0], "", supportingTemplateFile[1]));
    }

    supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, invokerPackage), "index.js"));
    supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js"));

}
 
Example 13
Source File: TaskGenerateOpenApiTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void should_UseGivenProperties_when_applicationPropertiesDefinesThem()
        throws Exception {

    String applicationTitle = "My title";
    String applicationAPIVersion = "1.1.1";
    String applicationServer = "https://example.com";
    String applicationPrefix = "/api";
    String applicationServerDescription = "Example API server";
    StringBuilder applicationPropertiesBuilder = new StringBuilder();
    applicationPropertiesBuilder
            .append(OpenApiSpecGenerator.APPLICATION_TITLE).append("=")
            .append(applicationTitle).append("\n")
            .append(OpenApiSpecGenerator.APPLICATION_API_VERSION)
            .append("=").append(applicationAPIVersion).append("\n")
            .append(OpenApiSpecGenerator.SERVER).append("=")
            .append(applicationServer).append("\n")
            .append(OpenApiSpecGenerator.PREFIX).append("=")
            .append(applicationPrefix).append("\n")
            .append(OpenApiSpecGenerator.SERVER_DESCRIPTION).append("=")
            .append(applicationServerDescription);
    FileUtils.writeStringToFile(applicationPropertiesFile,
            applicationPropertiesBuilder.toString(),
            StandardCharsets.UTF_8);

    taskGenerateOpenApi = new TaskGenerateOpenApi(applicationPropertiesFile,
            javaSource,
            this.getClass().getClassLoader(),
            generatedOpenAPI);
    taskGenerateOpenApi.execute();

    OpenAPI generatedOpenAPI = getGeneratedOpenAPI();
    Info info = generatedOpenAPI.getInfo();
    Assert.assertEquals(
            "Generated OpenAPI should use given application title",
            applicationTitle, info.getTitle());
    Assert.assertEquals(
            "Generated OpenAPI should use given"
                    + "application API version",
            applicationAPIVersion, info.getVersion());

    List<Server> servers = generatedOpenAPI.getServers();
    Assert.assertEquals("Generated OpenAPI should a defined server", 1,
            servers.size());
    Assert.assertEquals("Generated OpenAPI should use given url server",
            applicationServer + applicationPrefix,
            servers.get(0).getUrl());

    Assert.assertEquals(
            "Generated OpenAPI should use given server description",
            applicationServerDescription, servers.get(0).getDescription());
}
 
Example 14
Source File: NodeJSExpressServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
    public void preprocessOpenAPI(OpenAPI openAPI) {
        URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
        String host = URLPathUtils.getProtocolAndHost(url);
        String port = URLPathUtils.getPort(url, defaultServerPort);
        String basePath = url.getPath();

        if (additionalProperties.containsKey(SERVER_PORT)) {
            port = additionalProperties.get(SERVER_PORT).toString();
        }
        this.additionalProperties.put(SERVER_PORT, port);

        if (openAPI.getInfo() != null) {
            Info info = openAPI.getInfo();
            if (info.getTitle() != null) {
                // when info.title is defined, use it for projectName
                // used in package.json
                projectName = info.getTitle()
                        .replaceAll("[^a-zA-Z0-9]", "-")
                        .replaceAll("^[-]*", "")
                        .replaceAll("[-]*$", "")
                        .replaceAll("[-]{2,}", "-")
                        .toLowerCase(Locale.ROOT);
                this.additionalProperties.put("projectName", projectName);
            }
        }

        // need vendor extensions
        Paths paths = openAPI.getPaths();
        if (paths != null) {
            for (String pathname : paths.keySet()) {
                PathItem path = paths.get(pathname);
                Map<HttpMethod, Operation> operationMap = path.readOperationsMap();
                if (operationMap != null) {
                    for (HttpMethod method : operationMap.keySet()) {
                        Operation operation = operationMap.get(method);
                        String tag = "default";
                        if (operation.getTags() != null && operation.getTags().size() > 0) {
                            tag = toApiName(operation.getTags().get(0));
                        }
                        if (operation.getOperationId() == null) {
                            operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
                        }
                        // add x-openapi-router-controller
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-controller") == null) {
//                            operation.addExtension("x-openapi-router-controller", sanitizeTag(tag) + "Controller");
//                        }
//                        // add x-openapi-router-service
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-service") == null) {
//                            operation.addExtension("x-openapi-router-service", sanitizeTag(tag) + "Service");
//                        }
                        if (operation.getExtensions() == null ||
                                operation.getExtensions().get("x-eov-operation-handler") == null) {
                            operation.addExtension("x-eov-operation-handler", "controllers/" + sanitizeTag(tag) + "Controller");
                        }
                    }
                }
            }
        }

    }
 
Example 15
Source File: StaticHtml2Generator.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) {
            // when jsProjectName is not specified, generate it from info.title
            jsProjectName = sanitizeName(dashize(info.getTitle()));
        }
    }

    // default values
    if (StringUtils.isBlank(jsProjectName)) {
        jsProjectName = "openapi-js-client";
    }
    if (StringUtils.isBlank(jsModuleName)) {
        jsModuleName = camelize(underscore(jsProjectName));
    }

    additionalProperties.put("jsProjectName", jsProjectName);
    additionalProperties.put("jsModuleName", jsModuleName);

    preparHtmlForGlobalDescription(openAPI);

    Map<String, Object> vendorExtensions = openAPI.getExtensions();
    if (vendorExtensions != null) {
        for (Map.Entry<String, Object> vendorExtension : vendorExtensions.entrySet()) {
            // Vendor extensions could be Maps (objects). If we wanted to iterate through them in our template files
            // without knowing the keys beforehand, the default `toString` method renders them unusable. Instead, we
            // convert them to JSON strings now, which means we can easily use them later.
            if (vendorExtension.getValue() instanceof Map) {
                this.vendorExtensions().put(vendorExtension.getKey(), Json.mapper().convertValue(vendorExtension.getValue(), JsonNode.class));
            } else {
                this.vendorExtensions().put(vendorExtension.getKey(), vendorExtension.getValue());
            }
        }
    }
    openAPI.setExtensions(this.vendorExtensions);

}
 
Example 16
Source File: JavascriptApolloClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (StringUtils.isBlank(projectName) && info.getTitle() != null) {
            // when projectName is not specified, generate it from info.title
            projectName = sanitizeName(dashize(info.getTitle()));
        }
        if (StringUtils.isBlank(projectVersion)) {
            // when projectVersion is not specified, use info.version
            projectVersion = escapeUnsafeCharacters(escapeQuotationMark(info.getVersion()));
        }
        if (projectDescription == null) {
            // when projectDescription is not specified, use info.description
            if (StringUtils.isEmpty(info.getDescription())) {
                projectDescription = "JS API client generated by OpenAPI Generator";
            } else {
                projectDescription = sanitizeName(info.getDescription());
            }
        }

        // when licenceName is not specified, use info.license
        if (additionalProperties.get(CodegenConstants.LICENSE_NAME) == null && info.getLicense() != null) {
            License license = info.getLicense();
            licenseName = license.getName();
        }
    }

    // default values
    if (StringUtils.isBlank(projectName)) {
        projectName = "openapi-js-client";
    }
    if (StringUtils.isBlank(moduleName)) {
        moduleName = camelize(underscore(projectName));
    }
    if (StringUtils.isBlank(projectVersion)) {
        projectVersion = "1.0.0";
    }
    if (projectDescription == null) {
        projectDescription = "Client library of " + projectName;
    }
    if (StringUtils.isBlank(licenseName)) {
        licenseName = "Unlicense";
    }

    additionalProperties.put(PROJECT_NAME, projectName);
    additionalProperties.put(MODULE_NAME, moduleName);
    additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
    additionalProperties.put(PROJECT_VERSION, projectVersion);
    additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName);
    additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
    additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
    additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
    additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
    additionalProperties.put(USE_INHERITANCE, supportsInheritance);
    additionalProperties.put(EMIT_JS_DOC, emitJSDoc);
    additionalProperties.put(NPM_REPOSITORY, npmRepository);

    // make api and model doc path available in mustache template
    additionalProperties.put("apiDocPath", apiDocPath);
    additionalProperties.put("modelDocPath", modelDocPath);

    String[][] supportingTemplateFiles = JAVASCRIPT_SUPPORTING_FILES;

    for (String[] supportingTemplateFile : supportingTemplateFiles) {
        supportingFiles.add(new SupportingFile(supportingTemplateFile[0], "", supportingTemplateFile[1]));
    }

    supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, invokerPackage), "index.js"));
    supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js"));

}
 
Example 17
Source File: ClojureClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (additionalProperties.containsKey(PROJECT_NAME)) {
        projectName = ((String) additionalProperties.get(PROJECT_NAME));
    }
    if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) {
        projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION));
    }
    if (additionalProperties.containsKey(PROJECT_VERSION)) {
        projectVersion = ((String) additionalProperties.get(PROJECT_VERSION));
    }
    if (additionalProperties.containsKey(BASE_NAMESPACE)) {
        baseNamespace = ((String) additionalProperties.get(BASE_NAMESPACE));
    }

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (projectName == null && info.getTitle() != null) {
            // when projectName is not specified, generate it from info.title
            projectName = dashize(info.getTitle());
        }
        if (projectVersion == null) {
            // when projectVersion is not specified, use info.version
            projectVersion = info.getVersion();
        }
        if (projectDescription == null) {
            // when projectDescription is not specified, use info.description
            projectDescription = info.getDescription();
        }

        if (info.getContact() != null) {
            Contact contact = info.getContact();
            if (additionalProperties.get(PROJECT_URL) == null) {
                additionalProperties.put(PROJECT_URL, contact.getUrl());
            }
        }
        if (info.getLicense() != null) {
            License license = info.getLicense();
            if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) {
                additionalProperties.put(PROJECT_LICENSE_NAME, license.getName());
            }
            if (additionalProperties.get(PROJECT_LICENSE_URL) == null) {
                additionalProperties.put(PROJECT_LICENSE_URL, license.getUrl());
            }
        }
    }

    // default values
    if (projectName == null) {
        projectName = "openapi-clj-client";
    }
    if (projectVersion == null) {
        projectVersion = "1.0.0";
    }
    if (projectDescription == null) {
        projectDescription = "Client library of " + projectName;
    }
    if (baseNamespace == null) {
        baseNamespace = dashize(projectName);
    }
    apiPackage = baseNamespace + ".api";
    modelPackage = baseNamespace + ".specs";

    additionalProperties.put(PROJECT_NAME, projectName);
    additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
    additionalProperties.put(PROJECT_VERSION, projectVersion);
    additionalProperties.put(BASE_NAMESPACE, baseNamespace);
    additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
    additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);

    final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace);
    supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj"));
    supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj"));
    supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
    supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}
 
Example 18
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);
    if (openAPI == null) {
        return;
    }
    if (openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem path = openAPI.getPaths().get(pathname);
            if (path.readOperations() == null) {
                continue;
            }
            for (Operation operation : path.readOperations()) {
                LOGGER.info("Processing operation " + operation.getOperationId());
                if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) {
                    String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json";
                    List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation));
                    String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
                    operation.addExtension("x-contentType", contentType);
                }
                String accepts = getAccept(openAPI, operation);
                operation.addExtension("x-accepts", accepts);

            }
        }
    }

    // TODO: Setting additionalProperties is not the responsibility of this method. These side-effects should be moved elsewhere to prevent unexpected behaviors.
    if (artifactVersion == null) {
        // If no artifactVersion is provided in additional properties, version from API specification is used.
        // If none of them is provided then fallbacks to default version
        if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION) && additionalProperties.get(CodegenConstants.ARTIFACT_VERSION) != null) {
            this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
        } else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
            this.setArtifactVersion(openAPI.getInfo().getVersion());
        } else {
            this.setArtifactVersion(ARTIFACT_VERSION_DEFAULT_VALUE);
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

    if (additionalProperties.containsKey(CodegenConstants.SNAPSHOT_VERSION)) {
        if (convertPropertyToBooleanAndWriteBack(CodegenConstants.SNAPSHOT_VERSION)) {
            this.setArtifactVersion(this.buildSnapshotVersion(this.getArtifactVersion()));
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

}
 
Example 19
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent)
        throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        validationResponse.setValid(false);
        for (String message : parseAttemptForV3.getMessages()) {
            OASParserUtil.addErrorToValidationResponse(validationResponse, message);
            if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
                ErrorItem errorItem = new ErrorItem();
                errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
                errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                validationResponse.getErrorItems().add(errorItem);
            }
        }
    } else {
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
        OASParserUtil.updateValidationResponseAsSuccess(
                validationResponse, apiDefinition, openAPI.getOpenapi(),
                info.getTitle(), info.getVersion(), null, info.getDescription(),
                (openAPI.getServers()==null || openAPI.getServers().isEmpty() ) ? null :
                        openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList())
        );
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) { // not a json (it is yaml)
                JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
                validationResponse.setJsonContent(jsonNode.toString());
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
 
Example 20
Source File: OpenApiInfoDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Info getPropertyObject(OpenAPI oasObject) {
  return oasObject.getInfo();
}