From bfe6ec3a8bf15c1f45ae3aaefb57c322b18ce7b7 Mon Sep 17 00:00:00 2001
From: Petar Hristov <hristov@itc.rwth-aachen.de>
Date: Tue, 14 Feb 2023 12:58:30 +0100
Subject: [PATCH] Fix: Using OpenAPI 6.3.0

---
 src/CodeGen/CodeGen.csproj                    |   2 +-
 src/CodeGen/CodeGenerator/CodeGenerator.cs    | 231 +++++++++---------
 .../CodeGenerator/CoscineCodeGenerator.cs     |  97 ++++----
 src/CodeGen/Program.cs                        |  17 +-
 4 files changed, 175 insertions(+), 172 deletions(-)

diff --git a/src/CodeGen/CodeGen.csproj b/src/CodeGen/CodeGen.csproj
index f308f7e..442678c 100644
--- a/src/CodeGen/CodeGen.csproj
+++ b/src/CodeGen/CodeGen.csproj
@@ -8,7 +8,7 @@
   </PropertyGroup>
 
   <ItemGroup>
-    <PackageReference Include="Coscine.Configuration" Version="1.6.0" />
+    <PackageReference Include="Coscine.Configuration" Version="2.1.0" />
   </ItemGroup>
 
 </Project>
diff --git a/src/CodeGen/CodeGenerator/CodeGenerator.cs b/src/CodeGen/CodeGenerator/CodeGenerator.cs
index 55461b5..97d952b 100644
--- a/src/CodeGen/CodeGenerator/CodeGenerator.cs
+++ b/src/CodeGen/CodeGenerator/CodeGenerator.cs
@@ -6,176 +6,175 @@ using System.Net;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 
-namespace Coscine.CodeGen.CodeGenerator
+namespace Coscine.CodeGen.CodeGenerator;
+
+public abstract class CodeGenerator
 {
-    public abstract class CodeGenerator
+    #region Functionality
+    public async Task GenerateCode()
     {
-        #region Functionality
-        public async Task GenerateCode()
-        {
-            var jarFileName = await GetClientGenerator();
-
-            var keys = await GetApiNames();
+        var jarFileName = await GetClientGenerator();
 
-            var outputPath = await GetOutputPath();
-
-            if (!Directory.Exists(outputPath))
-            {
-                Directory.CreateDirectory(outputPath);
-            }
+        var keys = await GetApiNames();
 
-            await RetrieveDefinitions(outputPath, jarFileName, keys);
+        var outputPath = await GetOutputPath();
 
-            await WriteDefinitions(outputPath);
+        if (!Directory.Exists(outputPath))
+        {
+            Directory.CreateDirectory(outputPath);
         }
 
-        private async Task<string> RetrieveDefinitions(string outputPath, string jarFileName, IEnumerable<string> keys)
-        {
-            var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
-            var hostName = Dns.GetHostName();
+        await RetrieveDefinitions(outputPath, jarFileName, keys);
 
-            foreach (var key in keys)
-            {
-                Console.WriteLine(key);
+        await WriteDefinitions(outputPath);
+    }
 
-                var swaggerUrl = await GetSwaggerUrl(domainName, hostName, key);
-                var command = GetGenerationCommand(outputPath, jarFileName, key, swaggerUrl);
+    private async Task<string> RetrieveDefinitions(string outputPath, string jarFileName, IEnumerable<string> keys)
+    {
+        var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
+        var hostName = Dns.GetHostName();
 
-                await ExecuteCommand(command);
-            }
+        foreach (var key in keys)
+        {
+            Console.WriteLine(key);
+
+            var swaggerUrl = await GetSwaggerUrl(domainName, hostName, key);
+            var command = GetGenerationCommand(outputPath, jarFileName, key, swaggerUrl);
 
-            return outputPath;
+            await ExecuteCommand(command);
         }
 
-        private async Task WriteDefinitions(string outputPath)
-        {
-            var combinationFile = outputPath + "/apis.ts";
-            var indexFile = outputPath + "/index.ts";
+        return outputPath;
+    }
 
-            var combinationFileImports = new List<string>();
-            var combinationFileExports = new List<string>();
+    private async Task WriteDefinitions(string outputPath)
+    {
+        var combinationFile = outputPath + "/apis.ts";
+        var indexFile = outputPath + "/index.ts";
 
-            var concreteApiNames = new List<string>();
+        var combinationFileImports = new List<string>();
+        var combinationFileExports = new List<string>();
 
-            var first = true;
+        var concreteApiNames = new List<string>();
 
-            var apiRegex = new Regex("(?<= )(.*?)(?= extends BaseAPI)");
+        var first = true;
 
-            foreach (var directory in Directory.GetDirectories(outputPath))
-            {
-                var apiName = directory[(directory.LastIndexOf(".") + 1)..];
-                var directoryName = directory[(directory.LastIndexOf("\\") + 1)..];
+        var apiRegex = new Regex("(?<= )(.*?)(?= extends BaseAPI)");
 
-                apiName = apiName.Replace("Resources", "Resource");
-                apiName = apiName.Replace("Notices", "Notice");
+        foreach (var directory in Directory.GetDirectories(outputPath))
+        {
+            var apiName = directory[(directory.LastIndexOf(".") + 1)..];
+            var directoryName = directory[(directory.LastIndexOf("\\") + 1)..];
+
+            apiName = apiName.Replace("Resources", "Resource");
+            apiName = apiName.Replace("Notices", "Notice");
 
-                var apiContent = File.ReadAllText($"./{outputPath}/{directoryName}/api.ts");
+            var apiContent = File.ReadAllText($"./{outputPath}/{directoryName}/api.ts");
 
-                var apiImplementations = apiRegex.Matches(apiContent);
+            var apiImplementations = apiRegex.Matches(apiContent);
 
-                var customBasePath = await GetCustomBasePath(directoryName);
+            var customBasePath = await GetCustomBasePath(directoryName);
 
-                foreach (var apiImplementation in apiImplementations)
+            foreach (var apiImplementation in apiImplementations)
+            {
+                var concreteApiName = apiImplementation.ToString().Replace("class ", "");
+                concreteApiNames.Add(concreteApiName);
+                combinationFileImports.Add($"import {{ {concreteApiName}Factory }} from './{directoryName}/api';");
+                if (first)
                 {
-                    var concreteApiName = apiImplementation.ToString().Replace("class ", "");
-                    concreteApiNames.Add(concreteApiName);
-                    combinationFileImports.Add($"import {{ {concreteApiName}Factory }} from './{directoryName}/api';");
-                    if (first)
-                    {
-                        first = false;
-                        combinationFileImports.Add($"import {{ Configuration }} from './{directoryName}/configuration';");
-                    }
-                    combinationFileExports.Add($"{concreteApiName}: {concreteApiName}Factory(new Configuration({{ 'accessToken': accessToken }}), '{customBasePath}', axios)");
+                    first = false;
+                    combinationFileImports.Add($"import {{ Configuration }} from './{directoryName}/configuration';");
                 }
+                combinationFileExports.Add($"{concreteApiName}: {concreteApiName}Factory(new Configuration({{ 'accessToken': accessToken }}), '{customBasePath}', axios)");
             }
+        }
 
-            combinationFileExports.Sort();
-            concreteApiNames.Sort();
+        combinationFileExports.Sort();
+        concreteApiNames.Sort();
 
-            await WriteCombinationFile(combinationFile, combinationFileImports, combinationFileExports);
-            await WriteIndexFile(indexFile, concreteApiNames);
-        }
+        await WriteCombinationFile(combinationFile, combinationFileImports, combinationFileExports);
+        await WriteIndexFile(indexFile, concreteApiNames);
+    }
 
-        private async Task WriteCombinationFile(string combinationFile, IEnumerable<string> combinationFileImports, IEnumerable<string> combinationFileExports)
-        {
-            var combinationFileText = "import { AxiosInstance } from 'axios';\n\n";
-            combinationFileText += string.Join('\n', combinationFileImports);
-            combinationFileText += "\n\n";
+    private async Task WriteCombinationFile(string combinationFile, IEnumerable<string> combinationFileImports, IEnumerable<string> combinationFileExports)
+    {
+        var combinationFileText = "import { AxiosInstance } from 'axios';\n\n";
+        combinationFileText += string.Join('\n', combinationFileImports);
+        combinationFileText += "\n\n";
 
-            combinationFileText = await GetCustomCodeForCombinationFile(combinationFileText);
+        combinationFileText = await GetCustomCodeForCombinationFile(combinationFileText);
 
-            combinationFileText += @"function implementations(axios?: AxiosInstance) {
+        combinationFileText += @"function implementations(axios?: AxiosInstance) {
   return {
     ";
-            combinationFileText += string.Join(",\n    ", combinationFileExports);
-            combinationFileText += "\n  };\n};\n\nexport default implementations;\n";
+        combinationFileText += string.Join(",\n    ", combinationFileExports);
+        combinationFileText += "\n  };\n};\n\nexport default implementations;\n";
 
-            await File.WriteAllTextAsync(combinationFile, combinationFileText);
-        }
+        await File.WriteAllTextAsync(combinationFile, combinationFileText);
+    }
 
-        private async Task WriteIndexFile(string indexFile, IEnumerable<string> concreteApiNames)
-        {
-            var indexFileText = @"import implementations from './apis';
+    private async Task WriteIndexFile(string indexFile, IEnumerable<string> concreteApiNames)
+    {
+        var indexFileText = @"import implementations from './apis';
 import instance from './axios-basic';
 
 const apis = implementations(instance);
 
 ";
-            foreach (var concreteApiName in concreteApiNames)
-            {
-                indexFileText += $"export const {concreteApiName} = apis.{concreteApiName};\n";
-            }
-            indexFileText += "\nexport default apis;\n";
-
-            await File.WriteAllTextAsync(indexFile, indexFileText);
+        foreach (var concreteApiName in concreteApiNames)
+        {
+            indexFileText += $"export const {concreteApiName} = apis.{concreteApiName};\n";
         }
+        indexFileText += "\nexport default apis;\n";
 
-        internal Task ExecuteCommand(string command)
+        await File.WriteAllTextAsync(indexFile, indexFileText);
+    }
+
+    internal Task ExecuteCommand(string command)
+    {
+        var startInfo = new ProcessStartInfo
         {
-            var startInfo = new ProcessStartInfo
-            {
-                FileName = @"C:\Windows\System32\cmd.exe",
-                Arguments = "/c " + command,
-                RedirectStandardOutput = true,
-                RedirectStandardError = true,
-                UseShellExecute = false,
-                CreateNoWindow = true,
-            };
-            using (var process = new Process
-            {
-                StartInfo = startInfo
-            })
-            {
-                process.Start();
+            FileName = @"C:\Windows\System32\cmd.exe",
+            Arguments = "/c " + command,
+            RedirectStandardOutput = true,
+            RedirectStandardError = true,
+            UseShellExecute = false,
+            CreateNoWindow = true,
+        };
+        using (var process = new Process
+        {
+            StartInfo = startInfo
+        })
+        {
+            process.Start();
 
-                var outputTask = process.StandardOutput.ReadToEndAsync();
+            var outputTask = process.StandardOutput.ReadToEndAsync();
 
-                var errorTask = process.StandardError.ReadToEndAsync();
+            var errorTask = process.StandardError.ReadToEndAsync();
 
-                Task.WaitAll(outputTask, errorTask);
+            Task.WaitAll(outputTask, errorTask);
 
-                Console.WriteLine(outputTask.Result);
-                Console.WriteLine(errorTask.Result);
+            Console.WriteLine(outputTask.Result);
+            Console.WriteLine(errorTask.Result);
 
-                return process.WaitForExitAsync();
-            }
+            return process.WaitForExitAsync();
         }
-        #endregion
+    }
+    #endregion
 
-        #region Abstract Methods
-        public abstract Task<string> GetClientGenerator();
+    #region Abstract Methods
+    public abstract Task<string> GetClientGenerator();
 
-        public abstract Task<IEnumerable<string>> GetApiNames();
+    public abstract Task<IEnumerable<string>> GetApiNames();
 
-        internal abstract Task<string> GetOutputPath();
+    internal abstract Task<string> GetOutputPath();
 
-        internal abstract Task<string> GetSwaggerUrl(string domainName, string hostName, string key);
+    internal abstract Task<string> GetSwaggerUrl(string domainName, string hostName, string key);
 
-        internal abstract string GetGenerationCommand(string outputPath, string jarFileName, string key, string swaggerUrl);
+    internal abstract string GetGenerationCommand(string outputPath, string jarFileName, string key, string swaggerUrl);
 
-        internal abstract Task<string> GetCustomBasePath(string directoryName);
+    internal abstract Task<string> GetCustomBasePath(string directoryName);
 
-        internal abstract Task<string> GetCustomCodeForCombinationFile(string combinationFileText);
-        #endregion
-    }
+    internal abstract Task<string> GetCustomCodeForCombinationFile(string combinationFileText);
+    #endregion
 }
diff --git a/src/CodeGen/CodeGenerator/CoscineCodeGenerator.cs b/src/CodeGen/CodeGenerator/CoscineCodeGenerator.cs
index f51b7b8..ec55b0f 100644
--- a/src/CodeGen/CodeGenerator/CoscineCodeGenerator.cs
+++ b/src/CodeGen/CodeGenerator/CoscineCodeGenerator.cs
@@ -1,68 +1,74 @@
 using Coscine.Configuration;
 using System;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
-using System.Net;
+using System.Net.Http;
 using System.Threading.Tasks;
 
-namespace Coscine.CodeGen.CodeGenerator
+namespace Coscine.CodeGen.CodeGenerator;
+
+public class CoscineCodeGenerator : CodeGenerator
 {
-    public class CoscineCodeGenerator : CodeGenerator
-    {
-        private readonly IConfiguration _configuration;
+    private readonly IConfiguration _configuration;
 
-        public CoscineCodeGenerator(IConfiguration configuration)
-        {
-            this._configuration = configuration;
-        }
+    public CoscineCodeGenerator(IConfiguration configuration)
+    {
+        this._configuration = configuration;
+    }
 
-        public async override Task<string> GetClientGenerator()
-        {
-            var jarDownloadLink = await _configuration.GetStringAsync("coscine/local/codegen/jarlink",
-                            "https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.2.1/openapi-generator-cli-5.2.1.jar"
-                        );
+    public async override Task<string> GetClientGenerator()
+    {
+        var jarDownloadLink = await _configuration.GetStringAsync("coscine/local/codegen/jarlink", "https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.3.0/openapi-generator-cli-6.3.0.jar");
 
-            var webClient = new WebClient();
+        using var httpClient = new HttpClient();
+        var jarFileName = await _configuration.GetStringAsync("coscine/local/codegen/jarpath", "./codegen.jar");
 
-            var jarFileName = await _configuration.GetStringAsync("coscine/local/codegen/jarpath", "codegen.jar");
+        var response = await httpClient.GetAsync(new Uri(jarDownloadLink));
 
-            await webClient.DownloadFileTaskAsync(new Uri(jarDownloadLink), jarFileName);
-            return jarFileName;
+        using (var stream = await response.Content.ReadAsStreamAsync())
+        using (var fileStream = new FileStream(jarFileName, FileMode.Create))
+        {
+            await stream.CopyToAsync(fileStream);
         }
 
-        public async override Task<IEnumerable<string>> GetApiNames()
-        {
-            var apiPrefix = "coscine/apis/";
+        return jarFileName;
+    }
 
-            var keys = await _configuration.KeysAsync(apiPrefix);
-            return keys.Select((entry) => entry.Split('/')[2]).Distinct();
-        }
+    public async override Task<IEnumerable<string>> GetApiNames()
+    {
+        var apiPrefix = "coscine/apis/";
 
-        internal async override Task<string> GetOutputPath()
-        {
-            return await _configuration.GetStringAsync("coscine/local/codegen/outputpath", "Output");
-        }
+        var keys = await _configuration.KeysAsync(apiPrefix);
+        return keys.Select((entry) => entry.Split('/')[2]).Distinct();
+    }
 
-        internal override Task<string> GetSwaggerUrl(string domainName, string hostName, string key)
-        {
-            return Task.FromResult($"https://{hostName}.{domainName}/coscine/api/{key}/swagger/v1/swagger.json");
-        }
+    internal async override Task<string> GetOutputPath()
+    {
+        return await _configuration.GetStringAsync("coscine/local/codegen/outputpath", "Output");
+    }
 
-        internal override string GetGenerationCommand(string outputPath, string jarFileName, string key, string swaggerUrl)
-        {
-            return $"java \"-Dio.swagger.parser.util.RemoteUrl.trustAll=true\" \"-Dio.swagger.v3.parser.util.RemoteUrl.trustAll=true\" -jar \"{jarFileName}\" generate -i \"{swaggerUrl}\" -g typescript-axios -o \"{outputPath}/{key}\" --skip-validate-spec";
-        }
+    internal override Task<string> GetSwaggerUrl(string domainName, string hostName, string key)
+    {
+        return Task.FromResult($"https://{hostName}.{domainName}/coscine/api/{key}/swagger/v1/swagger.json");
+    }
 
-        internal override Task<string> GetCustomBasePath(string directoryName)
-        {
-            return Task.FromResult($"https://' + getHostName() + '/coscine/api/{directoryName}");
-        }
+    internal override string GetGenerationCommand(string outputPath, string jarFileName, string key, string swaggerUrl)
+    {
+        return $"java \"-Dio.swagger.parser.util.RemoteUrl.trustAll=true\" \"-Dio.swagger.v3.parser.util.RemoteUrl.trustAll=true\" -jar \"{jarFileName}\" generate -i \"{swaggerUrl}\" -g typescript-axios -o \"{outputPath}/{key}\" --skip-validate-spec";
+    }
 
-        internal override Task<string> GetCustomCodeForCombinationFile(string combinationFileText)
-        {
-            combinationFileText += "let accessToken = '';";
+    internal override Task<string> GetCustomBasePath(string directoryName)
+    {
+        return Task.FromResult($"https://' + getHostName() + '/coscine/api/{directoryName}");
+    }
+
+    internal override Task<string> GetCustomCodeForCombinationFile(string combinationFileText)
+    {
+        combinationFileText += "let accessToken = '';";
 
-            combinationFileText += @"
+        // Keep it like that for formatting
+        combinationFileText += @"
 if (typeof coscine !== 'undefined' && typeof coscine.authorization !== 'undefined') {
   accessToken = 'Bearer ' + coscine.authorization.bearer;
 }
@@ -86,7 +92,6 @@ const getHostName = () => {
 };
 
 ";
-            return Task.FromResult(combinationFileText);
-        }
+        return Task.FromResult(combinationFileText);
     }
 }
diff --git a/src/CodeGen/Program.cs b/src/CodeGen/Program.cs
index 65fffa3..5b88b00 100644
--- a/src/CodeGen/Program.cs
+++ b/src/CodeGen/Program.cs
@@ -1,14 +1,13 @@
-using Coscine.Configuration;
-using Coscine.CodeGen.CodeGenerator;
+using Coscine.CodeGen.CodeGenerator;
+using Coscine.Configuration;
 
-namespace Coscine.CodeGen
+namespace Coscine.CodeGen;
+
+public class Program
 {
-    public class Program
+    public static void Main(string[] args)
     {
-        public static void Main(string[] args)
-        {
-            new CoscineCodeGenerator(new ConsulConfiguration()).GenerateCode().GetAwaiter().GetResult();
-        }
-
+        new CoscineCodeGenerator(new ConsulConfiguration()).GenerateCode().GetAwaiter().GetResult();
     }
+
 }
-- 
GitLab