private async Task <JObject> GetOpenApiSpecificationFromBlobStorageAsync()
        {
            var openApiDocument = new OpenApiDocument();

            _logger.LogInformation("Retrieving OpenAPI Specification from blob storage.");

            try
            {
                var cloudBlockBlob = _cloudBlobContainer.GetBlockBlobReference(_appSettings.BlobName);

                var ms = new MemoryStream();

                await cloudBlockBlob.DownloadToStreamAsync(ms);

                ms.Seek(0, SeekOrigin.Begin);

                // Only using OpenApiDocument to allow validation and conversion of yaml into json.
                openApiDocument = new OpenApiStreamReader().Read(ms, out var diagnostic);

                if (diagnostic.Errors.Any())
                {
                    _logger.LogWarning("Diagnostic error reading open api document.", args: diagnostic.Errors);
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, e.Message);
            }
            finally
            {
                _logger.LogInformation("Finished retrieving OpenAPI Specification.");
            }

            return(JObject.Parse(openApiDocument.Serialize(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json)));
        }
Esempio n. 2
0
        internal byte[] ConvertOpenApiDocument(string inputFileContent, OpenApiSpecVersion apiSpecVersion, OpenApiFormat apiFormat)
        {
            using (Stream stream = this.CreateStream(inputFileContent))
            {
                var document = new OpenApiStreamReader().Read(stream, out var context);

                this.codeGeneratorProgress?.Progress(50, 100);

                var outputStream = new MemoryStream();
                document.Serialize(outputStream, apiSpecVersion, apiFormat);

                this.codeGeneratorProgress?.Progress(100, 100);
                var encoding = Encoding.GetEncoding(Encoding.UTF8.WindowsCodePage);

                //Get the preamble (byte-order mark) for our encoding
                byte[] preamble       = encoding.GetPreamble();
                int    preambleLength = preamble.Length;

                outputStream.Position = 0;

                //Convert the writer contents to a byte array
                byte[] body = encoding.GetBytes(new StreamReader(outputStream).ReadToEnd());

                //Prepend the preamble to body (store result in resized preamble array)
                Array.Resize(ref preamble, preambleLength + body.Length);
                Array.Copy(body, 0, preamble, preambleLength, body.Length);

                //Return the combined byte array
                return(preamble);
            }
        }
Esempio n. 3
0
        static async Task Main(string[] args)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://raw.githubusercontent.com/microsoft/appcenter-cli/")
            };

            var stream = await httpClient.GetStreamAsync("master/swagger/bifrost.swagger.json");

// Read V3 as YAML
            var openApiDocument = new OpenApiStreamReader().Read(stream, out var diagnostic);

// Write V2 as JSON
            var outputString = openApiDocument.Serialize(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json);

            Console.Write(outputString);
        }
        public async Task <JToken> LoadSchemaAsync(IEnumerable <string> documentUris, string?authorization)
        {
            var docs = documentUris.ToArray();

            if (docs.Length != 1)
            {
                throw new ArgumentException($"Cannot load multiple OpenApiSchema using this loader [{nameof(OpenApiSchemaLoader)}]", nameof(documentUris));
            }
            var documentUri = docs[0];

            var settings = new OpenApiReaderSettings()
            {
                //ReferenceResolution = ReferenceResolutionSetting.ResolveAllReferences,
            };

            using (var stream = await httpClient.GetStreamAsync(documentUri))
            {
                var openApiDocument = new OpenApiStreamReader(settings).Read(stream, out var diagnostic);

                var resolver = new OpenApiReferenceResolver(openApiDocument);
                var walker   = new OpenApiWalker(resolver);
                walker.Walk(openApiDocument);
                foreach (var item in resolver.Errors)
                {
                    diagnostic.Errors.Add(item);
                }

                if (diagnostic.Errors.Count != 0)
                {
                    var message = string.Join(Environment.NewLine, diagnostic.Errors);
                    throw new InvalidOperationException(message);
                }

                var apiV3Json = openApiDocument.Serialize(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json);
                return(JToken.Parse(apiV3Json));
            }
        }
Esempio n. 5
0
        public static void ProcessOpenApiDocument(
            FileInfo input,
            FileInfo output,
            OpenApiSpecVersion version,
            OpenApiFormat format,
            bool inline)
        {
            OpenApiDocument document;

            using (Stream stream = input.OpenRead())
            {
                document = new OpenApiStreamReader(new OpenApiReaderSettings
                {
                    ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
                    RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
                }
                                                   ).Read(stream, out var context);
                if (context.Errors.Count != 0)
                {
                    var errorReport = new StringBuilder();

                    foreach (var error in context.Errors)
                    {
                        errorReport.AppendLine(error.ToString());
                    }

                    throw new ArgumentException(String.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray()));
                }
            }

            using (var outputStream = output?.Create())
            {
                TextWriter textWriter;

                if (outputStream != null)
                {
                    textWriter = new StreamWriter(outputStream);
                }
                else
                {
                    textWriter = Console.Out;
                }

                var settings = new OpenApiWriterSettings()
                {
                    ReferenceInline = inline == true ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences
                };
                IOpenApiWriter writer;
                switch (format)
                {
                case OpenApiFormat.Json:
                    writer = new OpenApiJsonWriter(textWriter, settings);
                    break;

                case OpenApiFormat.Yaml:
                    writer = new OpenApiYamlWriter(textWriter, settings);
                    break;

                default:
                    throw new ArgumentException("Unknown format");
                }

                document.Serialize(writer, version);

                textWriter.Flush();
            }
        }