Search in sources :

Example 1 with GenSrcFile

use of org.wso2.apimgt.gateway.cli.model.template.GenSrcFile in project product-microgateway by wso2.

the class CodegenUtils method writeGeneratedSources.

/**
 * Write generated templates.
 *
 * @param sources list of source files
 * @param srcPath source location
 * @param overwrite whether existing files overwrite or not
 * @throws IOException if file write went wrong
 */
public static void writeGeneratedSources(List<GenSrcFile> sources, Path srcPath, boolean overwrite) throws IOException {
    Path filePath;
    for (GenSrcFile file : sources) {
        filePath = srcPath.resolve(file.getFileName());
        if (Files.notExists(filePath)) {
            CodegenUtils.writeFile(filePath, file.getContent());
        } else {
            if (overwrite) {
                Files.delete(filePath);
                CodegenUtils.writeFile(filePath, file.getContent());
            }
        }
    }
}
Also used : Path(java.nio.file.Path) GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile)

Example 2 with GenSrcFile

use of org.wso2.apimgt.gateway.cli.model.template.GenSrcFile in project product-microgateway by wso2.

the class CodeGenerator method generate.

/**
 * Generates ballerina source for provided Open APIDetailedDTO Definition in {@code definitionPath}.
 * Generated source will be written to a ballerina package at {@code outPath}
 * <p>Method can be used for generating Ballerina mock services and clients</p>
 *
 * @throws IOException when file operations fail
 */
public void generate(String projectName, boolean overwrite) throws IOException {
    String projectSrcPath = CmdUtils.getProjectTargetModulePath((projectName));
    List<GenSrcFile> genFiles = new ArrayList<>();
    List<BallerinaService> serviceList = new ArrayList<>();
    String grpcDirLocation = CmdUtils.getGrpcDefinitionsDirPath(projectName);
    CodeGenerator.projectName = projectName;
    BallerinaToml ballerinaToml = new BallerinaToml();
    ballerinaToml.setToolkitHome(CmdUtils.getCLIHome());
    List<String> openAPIDirectoryLocations = new ArrayList<>();
    String importedApisPath = CmdUtils.getProjectGenAPIDefinitionPath(projectName);
    String devApisPath = CmdUtils.getProjectAPIFilesDirectoryPath(projectName);
    if (Files.exists(Paths.get(devApisPath))) {
        openAPIDirectoryLocations.add(devApisPath);
    }
    if (Files.exists(Paths.get(importedApisPath))) {
        openAPIDirectoryLocations.add(importedApisPath);
    }
    // to store the available interceptors for validation purposes
    OpenAPICodegenUtils.setInterceptors(projectName);
    openAPIDirectoryLocations.forEach(openApiPath -> {
        try {
            Files.walk(Paths.get(openApiPath)).filter(path -> {
                Path fileName = path.getFileName();
                return fileName != null && (fileName.toString().endsWith(CliConstants.JSON_EXTENSION) || fileName.toString().endsWith(CliConstants.YAML_EXTENSION));
            }).forEach(path -> {
                try {
                    OpenAPI openAPI = new OpenAPIV3Parser().read(path.toString());
                    String openAPIContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
                    String openAPIAsJson = OpenAPICodegenUtils.getOpenAPIAsJson(openAPI, openAPIContent, path);
                    String openAPIContentAsJson = openAPIAsJson;
                    if (path.toString().endsWith(CliConstants.YAML_EXTENSION)) {
                        openAPIContentAsJson = OpenAPICodegenUtils.convertYamlToJson(openAPIContent);
                    }
                    String openAPIVersion = OpenAPICodegenUtils.findSwaggerVersion(openAPIContentAsJson, false);
                    OpenAPICodegenUtils.validateOpenAPIDefinition(openAPI, path.toString(), openAPIVersion);
                    OpenAPICodegenUtils.setOauthSecuritySchemaList(openAPI);
                    OpenAPICodegenUtils.setSecuritySchemaList(openAPI);
                    OpenAPICodegenUtils.setOpenAPIDefinitionEndpointReferenceExtensions(openAPI.getExtensions());
                    ExtendedAPI api = OpenAPICodegenUtils.generateAPIFromOpenAPIDef(openAPI, openAPIAsJson);
                    BallerinaService definitionContext;
                    OpenAPICodegenUtils.setAdditionalConfigsDevFirst(api, openAPI, path.toString());
                    definitionContext = new BallerinaService().buildContext(openAPI, api);
                    genFiles.add(generateService(definitionContext));
                    serviceList.add(definitionContext);
                    ballerinaToml.addDependencies(definitionContext);
                    copySwaggerToResourcesFolder(api.getName(), api.getVersion(), path);
                } catch (BallerinaServiceGenException e) {
                    throw new CLIRuntimeException("Swagger definition cannot be parsed to ballerina code", e);
                } catch (IOException e) {
                    throw new CLIInternalException("File write operations failed during ballerina code " + "generation", e);
                }
            });
        } catch (IOException e) {
            throw new CLIInternalException("File write operations failed during ballerina code generation", e);
        }
    });
    // to process protobuf files
    if (Paths.get(grpcDirLocation).toFile().exists()) {
        Files.walk(Paths.get(grpcDirLocation)).filter(path -> {
            Path filename = path.getFileName();
            return filename != null && (filename.toString().endsWith(".proto"));
        }).forEach(path -> {
            String descriptorPath = CmdUtils.getProtoDescriptorPath(projectName, path.getFileName().toString());
            try {
                ArrayList<OpenAPI> openAPIs = new ProtobufParser().generateOpenAPI(path.toString(), descriptorPath);
                if (openAPIs.size() > 0) {
                    for (OpenAPI openAPI : openAPIs) {
                        String openAPIContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
                        OpenAPICodegenUtils.setOauthSecuritySchemaList(openAPI);
                        OpenAPICodegenUtils.setSecuritySchemaList(openAPI);
                        createProtoOpenAPIFile(projectName, openAPI);
                        BallerinaService definitionContext = generateDefinitionContext(openAPI, openAPIContent, path, true);
                        genFiles.add(generateService(definitionContext));
                        serviceList.add(definitionContext);
                        ballerinaToml.addDependencies(definitionContext);
                    }
                }
            } catch (IOException e) {
                throw new CLIRuntimeException("Protobuf file cannot be parsed to " + "ballerina code", e);
            } catch (BallerinaServiceGenException e) {
                throw new CLIInternalException("File write operations failed during the ballerina code " + "generation for the protobuf files", e);
            }
        });
    }
    genFiles.add(generateMainBal(serviceList));
    genFiles.add(generateOpenAPIJsonConstantsBal(serviceList));
    genFiles.add(generateTokenServices());
    genFiles.add(generateHealthCheckService());
    genFiles.add(generateCommonEndpoints());
    CodegenUtils.writeGeneratedSources(genFiles, Paths.get(projectSrcPath), overwrite);
    // generate Ballerina.toml file
    ballerinaToml.addLibs(projectName);
    GenSrcFile toml = generateBallerinaTOML(ballerinaToml);
    String tomlPath = CmdUtils.getProjectTargetGenDirectoryPath(projectName) + File.separator + CliConstants.BALLERINA_TOML_FILE;
    CodegenUtils.writeFile(Paths.get(tomlPath), toml.getContent());
    // copy the files inside the extensions folder.
    CmdUtils.copyFolder(CmdUtils.getProjectExtensionsDirectoryPath(projectName), projectSrcPath);
}
Also used : FieldValueResolver(com.github.jknack.handlebars.context.FieldValueResolver) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) Yaml(io.swagger.v3.core.util.Yaml) MapValueResolver(com.github.jknack.handlebars.context.MapValueResolver) BallerinaToml(org.wso2.apimgt.gateway.cli.model.template.BallerinaToml) LoggerFactory(org.slf4j.LoggerFactory) BallerinaService(org.wso2.apimgt.gateway.cli.model.template.service.BallerinaService) ProtobufParser(org.wso2.apimgt.gateway.cli.protobuf.ProtobufParser) ExtendedAPI(org.wso2.apimgt.gateway.cli.model.rest.ext.ExtendedAPI) CliConstants(org.wso2.apimgt.gateway.cli.constants.CliConstants) GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) CodegenUtils(org.wso2.apimgt.gateway.cli.utils.CodegenUtils) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Path(java.nio.file.Path) BallerinaServiceGenException(org.wso2.apimgt.gateway.cli.exception.BallerinaServiceGenException) Context(com.github.jknack.handlebars.Context) Logger(org.slf4j.Logger) Files(java.nio.file.Files) GeneratorConstants(org.wso2.apimgt.gateway.cli.constants.GeneratorConstants) IOException(java.io.IOException) FileSystem(java.nio.file.FileSystem) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) CLIInternalException(org.wso2.apimgt.gateway.cli.exception.CLIInternalException) List(java.util.List) OpenAPICodegenUtils(org.wso2.apimgt.gateway.cli.utils.OpenAPICodegenUtils) Paths(java.nio.file.Paths) CmdUtils(org.wso2.apimgt.gateway.cli.utils.CmdUtils) ListenerEndpoint(org.wso2.apimgt.gateway.cli.model.template.service.ListenerEndpoint) JavaBeanValueResolver(com.github.jknack.handlebars.context.JavaBeanValueResolver) FileSystems(java.nio.file.FileSystems) Template(com.github.jknack.handlebars.Template) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) Path(java.nio.file.Path) ProtobufParser(org.wso2.apimgt.gateway.cli.protobuf.ProtobufParser) ArrayList(java.util.ArrayList) IOException(java.io.IOException) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) BallerinaServiceGenException(org.wso2.apimgt.gateway.cli.exception.BallerinaServiceGenException) CLIInternalException(org.wso2.apimgt.gateway.cli.exception.CLIInternalException) ExtendedAPI(org.wso2.apimgt.gateway.cli.model.rest.ext.ExtendedAPI) BallerinaService(org.wso2.apimgt.gateway.cli.model.template.service.BallerinaService) BallerinaToml(org.wso2.apimgt.gateway.cli.model.template.BallerinaToml) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 3 with GenSrcFile

use of org.wso2.apimgt.gateway.cli.model.template.GenSrcFile in project product-microgateway by wso2.

the class ThrottlePolicyGenerator method generateGenericPolicies.

/**
 * Generate generic policies source.
 *
 * @param policies list of application policies
 * @return list of {@code GenSrcFile}
 * @throws IOException when file operations fail
 */
private List<GenSrcFile> generateGenericPolicies(List<ThrottlePolicyMapper> policies, GeneratorConstants.PolicyType type) throws IOException {
    ThrottlePolicy policyContext;
    if (policies == null) {
        return null;
    }
    List<GenSrcFile> sourceFiles = new ArrayList<>();
    for (ThrottlePolicyMapper policy : policies) {
        policyContext = new ThrottlePolicy().buildContext(policy, type);
        sourceFiles.add(generatePolicy(policyContext));
    }
    return sourceFiles;
}
Also used : GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) ThrottlePolicyMapper(org.wso2.apimgt.gateway.cli.model.rest.policy.ThrottlePolicyMapper) ArrayList(java.util.ArrayList) ThrottlePolicy(org.wso2.apimgt.gateway.cli.model.template.policy.ThrottlePolicy)

Example 4 with GenSrcFile

use of org.wso2.apimgt.gateway.cli.model.template.GenSrcFile in project product-microgateway by wso2.

the class ThrottlePolicyGenerator method generate.

/**
 * Generate ballerina and stream source for a given app and subs policies.
 *
 * @param outPath     Destination file path to save generated source files. If not provided
 *                    {@code definitionPath} will be used as the default destination path
 * @param projectName Project name
 * @throws IOException when file operations fail
 */
public void generate(String outPath, String projectName) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String policyFileLocation = CmdUtils.getProjectDirectoryPath(projectName) + File.separator + CliConstants.GW_DIST_POLICIES_FILE;
    ThrottlePolicyListMapper throttlePolicyListMapper = mapper.readValue(new File(policyFileLocation), ThrottlePolicyListMapper.class);
    // read application throttle policies and subscription throttle policies
    List<ThrottlePolicyMapper> applicationPolicies = throttlePolicyListMapper.getApplicationPolicies();
    List<ThrottlePolicyMapper> subscriptionPolicies = throttlePolicyListMapper.getSubscriptionPolicies();
    List<ThrottlePolicyMapper> resourcePolicies = throttlePolicyListMapper.getResourcePolicies();
    if (applicationPolicies == null && subscriptionPolicies == null && resourcePolicies == null) {
        return;
    }
    checkDuplicatePolicyNames(applicationPolicies, subscriptionPolicies, resourcePolicies);
    List<GenSrcFile> genFiles = new ArrayList<>();
    GenSrcFile initGenFile = generateInitBal(applicationPolicies, subscriptionPolicies, resourcePolicies);
    genFiles.add(initGenFile);
    CodegenUtils.writeGeneratedSources(genFiles, Paths.get(outPath), true);
}
Also used : GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) ThrottlePolicyListMapper(org.wso2.apimgt.gateway.cli.model.rest.policy.ThrottlePolicyListMapper) ThrottlePolicyMapper(org.wso2.apimgt.gateway.cli.model.rest.policy.ThrottlePolicyMapper) ArrayList(java.util.ArrayList) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with GenSrcFile

use of org.wso2.apimgt.gateway.cli.model.template.GenSrcFile in project product-microgateway by wso2.

the class ThrottlePolicyGenerator method generate.

public void generate(String outPath, List<ApplicationThrottlePolicyDTO> applicationPolicies, List<SubscriptionThrottlePolicyDTO> subscriptionPolicies) throws IOException {
    List<GenSrcFile> genFiles = new ArrayList<>();
    List<GenSrcFile> genAppFiles = generateApplicationPolicies(applicationPolicies);
    if (genAppFiles != null) {
        genFiles.addAll(genAppFiles);
    }
    List<GenSrcFile> genSubsFiles = generateSubscriptionPolicies(subscriptionPolicies);
    if (genSubsFiles != null) {
        genFiles.addAll(genSubsFiles);
    }
    GenSrcFile initGenFile = generateInitBal(applicationPolicies, subscriptionPolicies);
    genFiles.add(initGenFile);
    CodegenUtils.writeGeneratedSources(genFiles, Paths.get(outPath), true);
}
Also used : GenSrcFile(org.wso2.apimgt.gateway.cli.model.template.GenSrcFile) ArrayList(java.util.ArrayList)

Aggregations

GenSrcFile (org.wso2.apimgt.gateway.cli.model.template.GenSrcFile)9 ArrayList (java.util.ArrayList)7 File (java.io.File)3 Path (java.nio.file.Path)3 ThrottlePolicy (org.wso2.apimgt.gateway.cli.model.template.policy.ThrottlePolicy)3 FileSystem (java.nio.file.FileSystem)2 ThrottlePolicyMapper (org.wso2.apimgt.gateway.cli.model.rest.policy.ThrottlePolicyMapper)2 BallerinaService (org.wso2.apimgt.gateway.cli.model.template.service.BallerinaService)2 ListenerEndpoint (org.wso2.apimgt.gateway.cli.model.template.service.ListenerEndpoint)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1 Context (com.github.jknack.handlebars.Context)1 Template (com.github.jknack.handlebars.Template)1 FieldValueResolver (com.github.jknack.handlebars.context.FieldValueResolver)1 JavaBeanValueResolver (com.github.jknack.handlebars.context.JavaBeanValueResolver)1 MapValueResolver (com.github.jknack.handlebars.context.MapValueResolver)1 Yaml (io.swagger.v3.core.util.Yaml)1 OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)1 IOException (java.io.IOException)1