From dc76bbe1b0e3e5eddf045bec1fb9e2482bb8aa74 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Thu, 7 Sep 2023 18:51:32 +0100 Subject: [PATCH 1/9] [WIP - Java] Move all of the name mangling logic to the Refiner --- it/compare-generation.ps1 | 8 +- .../Refiners/CommonLanguageRefiner.cs | 23 +-- src/Kiota.Builder/Refiners/JavaRefiner.cs | 26 +++- .../Java/CodeClassDeclarationWriter.cs | 8 +- .../Writers/Java/CodeEnumWriter.cs | 6 +- .../Writers/Java/CodeMethodWriter.cs | 141 ++++++++++-------- .../Writers/Java/CodePropertyWriter.cs | 4 +- .../Writers/Java/JavaConventionService.cs | 8 +- 8 files changed, 132 insertions(+), 92 deletions(-) diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index c8c40cf710..0c8ff32561 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -62,7 +62,7 @@ $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory Start-Process "$kiotaExec" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "$kiotaExec" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") @@ -81,8 +81,10 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString1)) $HashString2 = (Get-ChildItem $tmpFolder2 -Recurse | where { ! $_.PSIsContainer } | Get-FileHash -Algorithm MD5).Hash | Out-String Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) -Write-Output "Folder 1: $tmpFolder1" -Write-Output "Folder 2: $tmpFolder2" +Write-Output "Folder Old: $tmpFolder1" +Write-Output "Folder New: $tmpFolder2" + +diff --color -r "$tmpFolder1" "$tmpFolder2" if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index f3ec22130b..ee43d355bc 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -137,6 +137,9 @@ protected static void ReplacePropertyNames(CodeElement current, HashSet PROPERTY " + currentProperty1.Name + " " + currentProperty1.Kind + " - " + currentProperty1.ExistsInBaseType + " " + current.Parent); + if (current is CodeProperty currentProperty && !currentProperty.ExistsInBaseType && propertyKindsToReplace!.Contains(currentProperty.Kind) && @@ -145,11 +148,14 @@ current.Parent is CodeClass parentClass && { var refinedName = refineAccessorName(currentProperty.Name); - if (string.IsNullOrEmpty(currentProperty.SerializationName) && !refinedName.Equals(currentProperty.Name, StringComparison.Ordinal)) - currentProperty.SerializationName = currentProperty.Name; + if (!refinedName.Equals(currentProperty.Name, StringComparison.Ordinal) && + !parentClass.Properties.Any(property => !property.Name.Equals(property.Name, StringComparison.Ordinal) && refinedName.Equals(property.Name, StringComparison.OrdinalIgnoreCase)))// ensure the refinement won't generate a duplicate + { + if (string.IsNullOrEmpty(currentProperty.SerializationName)) + currentProperty.SerializationName = currentProperty.Name; - if (!parentClass.Properties.Any(property => refinedName.Equals(property.Name, StringComparison.OrdinalIgnoreCase)))// ensure the refinement won't generate a duplicate parentClass.RenameChildElement(currentProperty.Name, refinedName); + } } CrawlTree(current, x => ReplacePropertyNames(x, propertyKindsToReplace!, refineAccessorName)); } @@ -182,13 +188,13 @@ current.Parent is CodeClass parentClass && ReturnType = (CodeTypeBase)currentProperty.Type.Clone(), Documentation = new() { - Description = $"Gets the {currentProperty.WireName} property value. {currentProperty.Documentation.Description}", + Description = $"Gets the {currentProperty.Name} property value. {currentProperty.Documentation.Description}", }, AccessedProperty = currentProperty, Deprecation = currentProperty.Deprecation, }).First(); currentProperty.Getter.Name = $"{getterPrefix}{accessorName}"; // so we don't get an exception for duplicate names when no prefix - var setter = parentClass.AddMethod(new CodeMethod + currentProperty.Setter = parentClass.AddMethod(new CodeMethod { Name = $"set-{accessorName}", Access = AccessModifier.Public, @@ -196,7 +202,7 @@ current.Parent is CodeClass parentClass && Kind = CodeMethodKind.Setter, Documentation = new() { - Description = $"Sets the {currentProperty.WireName} property value. {currentProperty.Documentation.Description}", + Description = $"Sets the {currentProperty.Name} property value. {currentProperty.Documentation.Description}", }, AccessedProperty = currentProperty, ReturnType = new CodeType @@ -207,10 +213,9 @@ current.Parent is CodeClass parentClass && }, Deprecation = currentProperty.Deprecation, }).First(); - setter.Name = $"{setterPrefix}{accessorName}"; // so we don't get an exception for duplicate names when no prefix - currentProperty.Setter = setter; + currentProperty.Setter.Name = $"{setterPrefix}{accessorName}"; // so we don't get an exception for duplicate names when no prefix - setter.AddParameter(new CodeParameter + currentProperty.Setter.AddParameter(new CodeParameter { Name = "value", Kind = CodeParameterKind.SetterValue, diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index 362d3e8599..f6a7b33a24 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -7,6 +8,7 @@ using Kiota.Builder.Configuration; using Kiota.Builder.Extensions; using Kiota.Builder.Writers.Java; +using Microsoft.VisualBasic; namespace Kiota.Builder.Refiners; public class JavaRefiner : CommonLanguageRefiner, ILanguageRefiner @@ -17,6 +19,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance return Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); + CorrectCommonNames(generatedCode); MoveRequestBuilderPropertiesToBaseType(generatedCode, new CodeUsing { @@ -52,7 +55,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance InsertOverrideMethodForRequestExecutorsAndBuildersAndConstructors(generatedCode); ReplaceIndexersByMethodsWithParameter(generatedCode, true, - static x => $"By{x.ToFirstCharacterUpperCase()}", + static x => $"by{x.ToFirstCharacterUpperCase()}", static x => x.ToFirstCharacterLowerCase(), GenerationLanguage.Java); cancellationToken.ThrowIfCancellationRequested(); @@ -69,7 +72,9 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance ReplacePropertyNames(generatedCode, new() { CodePropertyKind.Custom, + CodePropertyKind.AdditionalData, CodePropertyKind.QueryParameter, + CodePropertyKind.RequestBuilder, }, static s => s.ToCamelCase(UnderscoreArray).ToFirstCharacterLowerCase()); AddGetterAndSetterMethods(generatedCode, @@ -78,7 +83,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance CodePropertyKind.AdditionalData, CodePropertyKind.BackingStore, }, - static (_, s) => s.ToCamelCase(UnderscoreArray), + static (_, s) => s.ToCamelCase(UnderscoreArray).ToFirstCharacterUpperCase(), _configuration.UsesBackingStore, true, "get", @@ -250,6 +255,19 @@ private static void AddEnumSetImport(CodeElement currentElement) AbstractionsNamespaceName, MultipartBodyClassName) }; private const string MultipartBodyClassName = "MultipartBody"; + private static void CorrectCommonNames(CodeElement currentElement) + { + if (currentElement is CodeMethod m) + { + m.Name = m.Name.ToFirstCharacterLowerCase(); + } + else if (currentElement is CodeIndexer i) + { + i.IndexParameter.Name = i.IndexParameter.Name.ToFirstCharacterLowerCase(); + } + + CrawlTree(currentElement, element => CorrectCommonNames(element)); + } private static void CorrectPropertyType(CodeProperty currentProperty) { if (currentProperty.IsOfKind(CodePropertyKind.RequestAdapter)) @@ -277,6 +295,7 @@ private static void CorrectPropertyType(CodeProperty currentProperty) if (!string.IsNullOrEmpty(currentProperty.DefaultValue)) currentProperty.DefaultValue = "new HashMap<>()"; } + currentProperty.Type.Name = currentProperty.Type.Name.ToFirstCharacterUpperCase(); CorrectCoreTypes(currentProperty.Parent as CodeClass, DateTypesReplacements, currentProperty.Type); } private static void CorrectImplements(ProprietableBlockDeclaration block) @@ -317,6 +336,9 @@ private static void CorrectMethodType(CodeMethod currentMethod) .Select(static x => x.Type) .Union(new[] { currentMethod.ReturnType }) .ToArray()); + + currentMethod.Parameters.ToList().ForEach(static x => x.Type.Name = x.Type.Name.ToFirstCharacterUpperCase()); + currentMethod.ReturnType.Name = currentMethod.ReturnType.Name.ToFirstCharacterUpperCase(); } private static readonly Dictionary DateTypesReplacements = new(StringComparer.OrdinalIgnoreCase) { {"DateTimeOffset", ("OffsetDateTime", new CodeUsing { diff --git a/src/Kiota.Builder/Writers/Java/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Java/CodeClassDeclarationWriter.cs index e7c0e7e8b3..d87f90d29a 100644 --- a/src/Kiota.Builder/Writers/Java/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeClassDeclarationWriter.cs @@ -21,8 +21,8 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .Where(static x => x.Declaration != null) .Where(x => x.Declaration!.IsExternal || !x.Declaration.Name.Equals(codeElement.Name, StringComparison.OrdinalIgnoreCase)) // needed for circular requests patterns like message folder .Select(static x => x.Declaration!.IsExternal ? - $"import {x.Declaration.Name}.{x.Name.ToFirstCharacterUpperCase()};" : - $"import {x.Name}.{x.Declaration.Name.ToFirstCharacterUpperCase()};") + $"import {x.Declaration.Name}.{x.Name};" : + $"import {x.Name}.{x.Declaration.Name};") .Distinct() .GroupBy(static x => x.Split('.').Last(), StringComparer.OrdinalIgnoreCase) .Select(static x => x.First()) // we don't want to import the same symbol twice @@ -30,13 +30,13 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .ToList() .ForEach(x => writer.WriteLine(x)); } - var derivation = (codeElement.Inherits == null ? string.Empty : $" extends {codeElement.Inherits.Name.ToFirstCharacterUpperCase()}") + + var derivation = (codeElement.Inherits == null ? string.Empty : $" extends {codeElement.Inherits.Name}") + (!codeElement.Implements.Any() ? string.Empty : $" implements {codeElement.Implements.Select(x => x.Name).Aggregate((x, y) => x + ", " + y)}"); if (codeElement.Parent is CodeClass parentClass) conventions.WriteLongDescription(parentClass, writer); var innerClassStatic = codeElement.Parent is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.Model) && currentClass.Parent is CodeClass ? "static " : string.Empty; //https://stackoverflow.com/questions/47541459/no-enclosing-instance-is-accessible-must-qualify-the-allocation-with-an-enclosi writer.WriteLine(JavaConventionService.AutoGenerationHeader); - writer.WriteLine($"public {innerClassStatic}class {codeElement.Name.ToFirstCharacterUpperCase()}{derivation} {{"); + writer.WriteLine($"public {innerClassStatic}class {codeElement.Name}{derivation} {{"); writer.IncreaseIndent(); } } diff --git a/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs index 410e416a88..68b3815149 100644 --- a/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs @@ -14,7 +14,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write var enumOptions = codeElement.Options.ToArray(); if (!enumOptions.Any()) return; - var enumName = codeElement.Name.ToFirstCharacterUpperCase(); + var enumName = codeElement.Name; writer.WriteLines($"package {(codeElement.Parent as CodeNamespace)?.Name};", string.Empty, "import com.microsoft.kiota.serialization.ValuedEnum;", @@ -29,7 +29,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write foreach (var enumOption in enumOptions) { conventions.WriteShortDescription(enumOption.Documentation.Description, writer); - writer.WriteLine($"{enumOption.Name.ToFirstCharacterUpperCase()}(\"{enumOption.SerializationName}\"){(enumOption == lastEnumOption ? ";" : ",")}"); + writer.WriteLine($"{enumOption.Name}(\"{enumOption.SerializationName}\"){(enumOption == lastEnumOption ? ";" : ",")}"); } writer.WriteLines("public final String value;", $"{enumName}(final String value) {{"); @@ -46,7 +46,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write "switch(searchValue) {"); writer.IncreaseIndent(); writer.Write(enumOptions - .Select(x => $"case \"{x.WireName}\": return {x.Name.ToFirstCharacterUpperCase()};") + .Select(x => $"case \"{x.WireName}\": return {x.Name};") .Aggregate((x, y) => $"{x}{LanguageWriter.NewLine}{writer.GetIndent()}{y}") + LanguageWriter.NewLine); writer.WriteLine("default: return null;"); writer.CloseBlock(); diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index cc1f0b79ba..51e171a286 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -19,12 +19,10 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement); if (codeElement.ReturnType is CodeType { TypeDefinition: CodeEnum { Flags: true }, IsCollection: false }) returnType = $"EnumSet<{returnType}>"; - if (codeElement.IsAsync && - codeElement.IsOfKind(CodeMethodKind.RequestExecutor) && - returnType.Equals("void", StringComparison.OrdinalIgnoreCase)) - returnType = "Void"; //generic type for the future - WriteMethodDocumentation(codeElement, writer, returnType); - WriteMethodPrototype(codeElement, writer, returnType); + var baseReturnType = conventions.GetTypeString(codeElement.ReturnType, codeElement); + var finalReturnType = GetFinalReturnType(codeElement, baseReturnType); + WriteMethodDocumentation(codeElement, writer, baseReturnType, finalReturnType); + WriteMethodPrototype(codeElement, writer, finalReturnType); writer.IncreaseIndent(); var inherits = parentClass.StartBlock.Inherits != null && !parentClass.IsErrorDefinition; var requestBodyParam = codeElement.Parameters.OfKind(CodeParameterKind.RequestBody); @@ -40,7 +38,7 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri WriteDeserializerBody(codeElement, parentClass, writer, inherits); break; case CodeMethodKind.IndexerBackwardCompatibility: - WriteIndexerBody(codeElement, parentClass, writer, returnType); + WriteIndexerBody(codeElement, parentClass, writer, finalReturnType); break; case CodeMethodKind.RequestGenerator when codeElement.IsOverload: WriteGeneratorOrExecutorMethodCall(codeElement, requestParams, parentClass, writer, "return ", CodeMethodKind.RequestGenerator); @@ -111,18 +109,18 @@ private void WriteRawUrlBuilderBody(CodeClass parentClass, CodeMethod codeElemen { var rawUrlParameter = codeElement.Parameters.OfKind(CodeParameterKind.RawUrl) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RawUrl parameter"); var requestAdapterProperty = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RequestAdapter property"); - writer.WriteLine($"return new {parentClass.Name.ToFirstCharacterUpperCase()}({rawUrlParameter.Name.ToFirstCharacterLowerCase()}, {requestAdapterProperty.Name.ToFirstCharacterLowerCase()});"); + writer.WriteLine($"return new {parentClass.Name}({rawUrlParameter.Name}, {requestAdapterProperty.Name});"); } private const string ResultVarName = "result"; private void WriteFactoryMethodBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) { var parseNodeParameter = codeElement.Parameters.OfKind(CodeParameterKind.ParseNode) ?? throw new InvalidOperationException("Factory method should have a ParseNode parameter"); if (parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForUnionType || parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType) - writer.WriteLine($"final {parentClass.Name.ToFirstCharacterUpperCase()} {ResultVarName} = new {parentClass.Name.ToFirstCharacterUpperCase()}();"); + writer.WriteLine($"final {parentClass.Name} {ResultVarName} = new {parentClass.Name}();"); var writeDiscriminatorValueRead = parentClass.DiscriminatorInformation.ShouldWriteParseNodeCheck && !parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType; if (writeDiscriminatorValueRead) { - writer.WriteLine($"final ParseNode mappingValueNode = {parseNodeParameter.Name.ToFirstCharacterLowerCase()}.getChildNode(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\");"); + writer.WriteLine($"final ParseNode mappingValueNode = {parseNodeParameter.Name}.getChildNode(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\");"); writer.StartBlock("if (mappingValueNode != null) {"); writer.WriteLine($"final String {DiscriminatorMappingVarName} = mappingValueNode.getStringValue();"); } @@ -146,7 +144,7 @@ private void WriteFactoryMethodBody(CodeMethod codeElement, CodeClass parentClas writer.WriteLine($"return {ResultVarName};"); } else - writer.WriteLine($"return new {parentClass.Name.ToFirstCharacterUpperCase()}();"); + writer.WriteLine($"return new {parentClass.Name}();"); } private static readonly Regex factoryMethodIndexParser = new(@"_(?\d+)", RegexOptions.Compiled, Constants.DefaultRegexTimeout); private static void WriteFactoryOverloadMethod(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) @@ -156,7 +154,7 @@ private static void WriteFactoryOverloadMethod(CodeMethod codeElement, CodeClass { var takeValue = Math.Min(MaxDiscriminatorsPerMethod, parentClass.DiscriminatorInformation.DiscriminatorMappings.Count() - currentDiscriminatorPageIndex * MaxDiscriminatorsPerMethod); var currentDiscriminatorPage = parentClass.DiscriminatorInformation.DiscriminatorMappings.Skip(currentDiscriminatorPageIndex * MaxDiscriminatorsPerMethod).Take(takeValue).OrderBy(static x => x.Key, StringComparer.OrdinalIgnoreCase); - WriteFactoryMethodBodyForInheritedModel(currentDiscriminatorPage, writer, parameter.Name.ToFirstCharacterLowerCase()); + WriteFactoryMethodBodyForInheritedModel(currentDiscriminatorPage, writer, parameter.Name); } writer.WriteLine("return null;"); } @@ -168,7 +166,7 @@ private static void WriteSplitFactoryMethodBodyForInheritedModel(CodeClass paren .OrderBy(static x => x, StringComparer.OrdinalIgnoreCase)) { var varName = $"{otherMethodName}_result"; - writer.WriteLine($"final {parentClass.Name.ToFirstCharacterUpperCase()} {varName} = {otherMethodName.ToFirstCharacterLowerCase()}({DiscriminatorMappingVarName});"); + writer.WriteLine($"final {parentClass.Name} {varName} = {otherMethodName}({DiscriminatorMappingVarName});"); writer.StartBlock($"if ({varName} != null) {{"); writer.WriteLine($"return {varName};"); writer.CloseBlock(); @@ -181,7 +179,7 @@ private static void WriteFactoryMethodBodyForInheritedModel(IOrderedEnumerable x.Item1.Setter != null)) - writer.WriteLine($"{ResultVarName}.{property.Item1.Setter!.Name.ToFirstCharacterLowerCase()}(new {conventions.GetTypeString(property.Item2, codeElement, false)}());"); + writer.WriteLine($"{ResultVarName}.{property.Item1.Setter!.Name}(new {conventions.GetTypeString(property.Item2, codeElement, false)}());"); if (includeElse) writer.CloseBlock(); } @@ -244,7 +242,7 @@ private void WriteFactoryMethodBodyForUnionModelForDiscriminatedTypes(CodeMethod }; var mappedType = parentClass.DiscriminatorInformation.DiscriminatorMappings.FirstOrDefault(x => x.Value.Name.Equals(property.Type.Name, StringComparison.OrdinalIgnoreCase)); writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (\"{mappedType.Key}\".equalsIgnoreCase({DiscriminatorMappingVarName})) {{"); - writer.WriteLine($"{ResultVarName}.{property.Setter!.Name.ToFirstCharacterLowerCase()}(new {conventions.GetTypeString(property.Type, codeElement, false)}());"); + writer.WriteLine($"{ResultVarName}.{property.Setter!.Name}(new {conventions.GetTypeString(property.Type, codeElement, false)}());"); writer.DecreaseIndent(); if (!includeElse) includeElse = true; @@ -264,9 +262,9 @@ private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeMeth { if (property.Type is CodeType propertyType) { - var serializationMethodName = $"{parseNodeParameter.Name.ToFirstCharacterLowerCase()}.{GetDeserializationMethodName(propertyType, currentElement)}"; + var serializationMethodName = $"{parseNodeParameter.Name}.{GetDeserializationMethodName(propertyType, currentElement)}"; writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if ({serializationMethodName} != null) {{"); - writer.WriteLine($"{ResultVarName}.{property.Setter!.Name.ToFirstCharacterLowerCase()}({serializationMethodName});"); + writer.WriteLine($"{ResultVarName}.{property.Setter!.Name}({serializationMethodName});"); writer.DecreaseIndent(); if (!includeElse) includeElse = true; @@ -284,7 +282,7 @@ private static void AddNullChecks(CodeMethod codeElement, LanguageWriter writer) { if (!codeElement.IsOverload) foreach (var parameter in codeElement.Parameters.Where(static x => !x.Optional && !x.IsOfKind(CodeParameterKind.RequestAdapter, CodeParameterKind.PathParameters)).OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"Objects.requireNonNull({parameter.Name.ToFirstCharacterLowerCase()});"); + writer.WriteLine($"Objects.requireNonNull({parameter.Name});"); } private static void WriteRequestBuilderConstructorCall(CodeMethod codeElement, LanguageWriter writer) { @@ -299,7 +297,7 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterProperty = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter); var pathParametersProperty = parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters); var backingStoreParameter = method.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.BackingStore)); - var requestAdapterPropertyName = requestAdapterProperty?.Name.ToFirstCharacterLowerCase() ?? string.Empty; + var requestAdapterPropertyName = requestAdapterProperty?.Name ?? string.Empty; WriteSerializationRegistration(method.SerializerModules, writer, "registerDefaultSerializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "registerDefaultDeserializer"); if (!string.IsNullOrEmpty(method.BaseUrl)) @@ -308,7 +306,7 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me writer.WriteLine($"{requestAdapterPropertyName}.setBaseUrl(\"{method.BaseUrl}\");"); writer.CloseBlock(); if (pathParametersProperty != null) - writer.WriteLine($"{pathParametersProperty.Name.ToFirstCharacterLowerCase()}.put(\"baseurl\", {requestAdapterPropertyName}.getBaseUrl());"); + writer.WriteLine($"{pathParametersProperty.Name}.put(\"baseurl\", {requestAdapterPropertyName}.getBaseUrl());"); } if (backingStoreParameter != null) writer.WriteLine($"this.{requestAdapterPropertyName}.enableBackingStore({backingStoreParameter.Name});"); @@ -332,7 +330,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho thirdParameterName = $", {pathParametersParameter.Name}"; else if (currentMethod.Parameters.OfKind(CodeParameterKind.RawUrl) is CodeParameter rawUrlParameter) thirdParameterName = $", {rawUrlParameter.Name}"; - writer.WriteLine($"super({requestAdapterParameter.Name.ToFirstCharacterLowerCase()}, {urlTemplateProperty.DefaultValue}{thirdParameterName});"); + writer.WriteLine($"super({requestAdapterParameter.Name}, {urlTemplateProperty.DefaultValue}{thirdParameterName});"); } else writer.WriteLine("super();"); @@ -342,7 +340,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho .Where(static x => !string.IsNullOrEmpty(x.DefaultValue)) .OrderBy(static x => x.Name)) { - writer.WriteLine($"this.{propWithDefault.NamePrefix}{propWithDefault.Name.ToFirstCharacterLowerCase()} = {propWithDefault.DefaultValue};"); + writer.WriteLine($"this.{propWithDefault.NamePrefix}{propWithDefault.Name} = {propWithDefault.DefaultValue};"); } foreach (var propWithDefault in parentClass.GetPropertiesOfKind(CodePropertyKind.AdditionalData, CodePropertyKind.Custom) //additional data and custom properties rely on accessors .Where(static x => !string.IsNullOrEmpty(x.DefaultValue)) @@ -350,11 +348,11 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho .Where(static x => x.Type is not CodeType propType || propType.TypeDefinition is not CodeClass propertyClass || propertyClass.OriginalComposedType is null) .OrderBy(static x => x.Name)) { - var setterName = propWithDefault.SetterFromCurrentOrBaseType?.Name.ToFirstCharacterLowerCase() is string sName && !string.IsNullOrEmpty(sName) ? sName : $"set{propWithDefault.Name.ToFirstCharacterUpperCase()}"; + var setterName = propWithDefault.SetterFromCurrentOrBaseType?.Name is string sName && !string.IsNullOrEmpty(sName) ? sName : $"set{propWithDefault.Name}"; var defaultValue = propWithDefault.DefaultValue; if (propWithDefault.Type is CodeType propertyType && propertyType.TypeDefinition is CodeEnum enumDefinition) { - defaultValue = $"{enumDefinition.Name.ToFirstCharacterUpperCase()}.forValue({defaultValue})"; + defaultValue = $"{enumDefinition.Name}.forValue({defaultValue})"; } writer.WriteLine($"this.{setterName}({defaultValue});"); } @@ -367,21 +365,21 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho if (pathParameters.Any()) conventions.AddParametersAssignment(writer, pathParametersParam.Type, - pathParametersParam.Name.ToFirstCharacterLowerCase(), - $"this.{pathParametersProp.Name.ToFirstCharacterLowerCase()}", + pathParametersParam.Name, + $"this.{pathParametersProp.Name}", pathParameters - .Select(static x => (x.Type, string.IsNullOrEmpty(x.SerializationName) ? x.Name : x.SerializationName, x.Name.ToFirstCharacterLowerCase())) + .Select(static x => (x.Type, string.IsNullOrEmpty(x.SerializationName) ? x.Name : x.SerializationName, x.Name)) .ToArray()); } } private static void WriteSetterBody(CodeMethod codeElement, LanguageWriter writer, CodeClass parentClass) { if (parentClass.GetBackingStoreProperty() is CodeProperty backingStore) - writer.WriteLine($"this.get{backingStore.Name.ToFirstCharacterUpperCase()}().set(\"{codeElement.AccessedProperty?.Name?.ToFirstCharacterLowerCase()}\", value);"); + writer.WriteLine($"this.get{backingStore.Name}().set(\"{codeElement.AccessedProperty?.Name}\", value);"); else { string value = "PeriodAndDuration".Equals(codeElement.AccessedProperty?.Type?.Name, StringComparison.OrdinalIgnoreCase) ? "PeriodAndDuration.ofPeriodAndDuration(value);" : "value;"; - writer.WriteLine($"this.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name?.ToFirstCharacterLowerCase()} = {value}"); + writer.WriteLine($"this.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name} = {value}"); } } @@ -389,28 +387,28 @@ private void WriteGetterBody(CodeMethod codeElement, LanguageWriter writer, Code { var backingStore = parentClass.GetBackingStoreProperty(); if (backingStore == null || (codeElement.AccessedProperty?.IsOfKind(CodePropertyKind.BackingStore) ?? false)) - writer.WriteLine($"return this.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name?.ToFirstCharacterLowerCase()};"); + writer.WriteLine($"return this.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name};"); else if (!(codeElement.AccessedProperty?.Type?.IsNullable ?? true) && !(codeElement.AccessedProperty?.ReadOnly ?? true) && !string.IsNullOrEmpty(codeElement.AccessedProperty?.DefaultValue)) { - writer.WriteLine($"{conventions.GetTypeString(codeElement.AccessedProperty.Type, codeElement)} value = this.{backingStore.NamePrefix}{backingStore.Name.ToFirstCharacterLowerCase()}.get(\"{codeElement.AccessedProperty.Name.ToFirstCharacterLowerCase()}\");"); + writer.WriteLine($"{conventions.GetTypeString(codeElement.AccessedProperty.Type, codeElement)} value = this.{backingStore.NamePrefix}{backingStore.Name}\");"); writer.StartBlock("if(value == null) {"); writer.WriteLines($"value = {codeElement.AccessedProperty.DefaultValue};", - $"this.set{codeElement.AccessedProperty?.Name?.ToFirstCharacterUpperCase()}(value);"); + $"this.set{codeElement.AccessedProperty?.Name}(value);"); writer.CloseBlock(); writer.WriteLine("return value;"); } else - writer.WriteLine($"return this.get{backingStore.Name.ToFirstCharacterUpperCase()}().get(\"{codeElement.AccessedProperty?.Name?.ToFirstCharacterLowerCase()}\");"); + writer.WriteLine($"return this.get{backingStore.Name}().get(\"{codeElement.AccessedProperty?.Name}\");"); } private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer, string returnType) { if (parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty && codeElement.OriginalIndexer != null) conventions.AddParametersAssignment(writer, pathParametersProperty.Type, $"this.{pathParametersProperty.Name}", - parameters: (codeElement.OriginalIndexer.IndexParameter.Type, codeElement.OriginalIndexer.IndexParameter.SerializationName, codeElement.OriginalIndexer.IndexParameter.Name.ToFirstCharacterLowerCase())); + parameters: (codeElement.OriginalIndexer.IndexParameter.Type, codeElement.OriginalIndexer.IndexParameter.SerializationName, codeElement.OriginalIndexer.IndexParameter.Name)); conventions.AddRequestBuilderBody(parentClass, returnType, writer, conventions.TempDictionaryVarName); } private void WriteDeserializerBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer, bool inherits) @@ -432,12 +430,12 @@ private static void WriteDeserializerBodyForUnionModel(CodeMethod method, CodeCl .Where(static x => x.Getter != null && x.Type is CodeType propertyType && !propertyType.IsCollection && propertyType.TypeDefinition is CodeClass) .OrderBy(static x => x, CodePropertyTypeForwardComparer) .ThenBy(static x => x.Name) - .Select(static x => x.Getter!.Name.ToFirstCharacterLowerCase()) + .Select(static x => x.Getter!.Name) .ToArray(); foreach (var otherPropGetter in otherPropGetters) { writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (this.{otherPropGetter}() != null) {{"); - writer.WriteLine($"return this.{otherPropGetter}().{method.Name.ToFirstCharacterLowerCase()}();"); + writer.WriteLine($"return this.{otherPropGetter}().{method.Name}();"); writer.DecreaseIndent(); if (!includeElse) includeElse = true; @@ -455,7 +453,7 @@ private static void WriteDeserializerBodyForIntersectionModel(CodeClass parentCl { var propertiesNames = complexProperties .Where(static x => x.Getter != null) - .Select(static x => x.Getter!.Name.ToFirstCharacterLowerCase()) + .Select(static x => x.Getter!.Name) .OrderBy(static x => x) .ToArray(); var propertiesNamesAsConditions = propertiesNames @@ -475,14 +473,14 @@ private void WriteDeserializerBodyForInheritedModel(CodeMethod method, CodeClass { var fieldToSerialize = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom).ToArray(); writer.WriteLines( - $"final {DeserializerReturnType} {DeserializerVarName} = new {DeserializerReturnType}({(inherits ? "super." + method.Name.ToFirstCharacterLowerCase() + "()" : fieldToSerialize.Length)});"); + $"final {DeserializerReturnType} {DeserializerVarName} = new {DeserializerReturnType}({(inherits ? "super." + method.Name + "()" : fieldToSerialize.Length)});"); if (fieldToSerialize.Any()) { fieldToSerialize .Where(static x => !x.ExistsInBaseType && x.Setter != null) .OrderBy(static x => x.Name) .Select(x => - $"{DeserializerVarName}.put(\"{x.WireName}\", (n) -> {{ this.{x.Setter!.Name.ToFirstCharacterLowerCase()}(n.{GetDeserializationMethodName(x.Type, method)}); }});") + $"{DeserializerVarName}.put(\"{x.WireName}\", (n) -> {{ this.{x.Setter!.Name}(n.{GetDeserializationMethodName(x.Type, method)}); }});") .ToList() .ForEach(x => writer.WriteLine(x)); } @@ -502,7 +500,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ writer.WriteLine($"final HashMap> {errorMappingVarName} = new HashMap>();"); foreach (var errorMapping in codeElement.ErrorMappings) { - writer.WriteLine($"{errorMappingVarName}.put(\"{errorMapping.Key.ToUpperInvariant()}\", {errorMapping.Value.Name.ToFirstCharacterUpperCase()}::{FactoryMethodName});"); + writer.WriteLine($"{errorMappingVarName}.put(\"{errorMapping.Key.ToUpperInvariant()}\", {errorMapping.Value.Name}::{FactoryMethodName});"); } } var factoryParameter = codeElement.ReturnType is CodeType returnCodeType && returnCodeType.TypeDefinition is CodeClass ? $"{returnType}::{FactoryMethodName}" : $"{returnType}.class"; @@ -557,26 +555,26 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req if (requestParams.requestBody != null && currentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) is CodeProperty requestAdapterProperty) { - var toArrayPostfix = requestParams.requestBody.Type.IsCollection ? $".toArray(new {requestParams.requestBody.Type.Name.ToFirstCharacterUpperCase()}[0])" : string.Empty; + var toArrayPostfix = requestParams.requestBody.Type.IsCollection ? $".toArray(new {requestParams.requestBody.Type.Name}[0])" : string.Empty; var collectionPostfix = requestParams.requestBody.Type.IsCollection ? "Collection" : string.Empty; if (requestParams.requestBody.Type.Name.Equals(conventions.StreamTypeName, StringComparison.OrdinalIgnoreCase)) writer.WriteLine($"{RequestInfoVarName}.setStreamContent({requestParams.requestBody.Name});"); else if (requestParams.requestBody.Type is CodeType bodyType && (bodyType.TypeDefinition is CodeClass || bodyType.Name.Equals("MultipartBody", StringComparison.OrdinalIgnoreCase))) - writer.WriteLine($"{RequestInfoVarName}.setContentFromParsable({requestAdapterProperty.Name.ToFirstCharacterLowerCase()}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name}{toArrayPostfix});"); + writer.WriteLine($"{RequestInfoVarName}.setContentFromParsable({requestAdapterProperty.Name}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name}{toArrayPostfix});"); else - writer.WriteLine($"{RequestInfoVarName}.setContentFromScalar{collectionPostfix}({requestAdapterProperty.Name.ToFirstCharacterLowerCase()}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name}{toArrayPostfix});"); + writer.WriteLine($"{RequestInfoVarName}.setContentFromScalar{collectionPostfix}({requestAdapterProperty.Name}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name}{toArrayPostfix});"); } if (requestParams.requestConfiguration != null) { writer.WriteLine($"if ({requestParams.requestConfiguration.Name} != null) {{"); writer.IncreaseIndent(); - var requestConfigTypeName = requestParams.requestConfiguration.Type.Name.ToFirstCharacterUpperCase(); + var requestConfigTypeName = requestParams.requestConfiguration.Type.Name; writer.WriteLines($"final {requestConfigTypeName} {RequestConfigVarName} = new {requestConfigTypeName}();", $"{requestParams.requestConfiguration.Name}.accept({RequestConfigVarName});"); var queryString = requestParams.QueryParameters; if (queryString != null) { - var queryStringName = $"{RequestConfigVarName}.{queryString.Name.ToFirstCharacterLowerCase()}"; + var queryStringName = $"{RequestConfigVarName}.{queryString.Name}"; writer.WriteLine($"{RequestInfoVarName}.addQueryParameters({queryStringName});"); } writer.WriteLines($"{RequestInfoVarName}.headers.putAll({RequestConfigVarName}.headers);", @@ -587,7 +585,7 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req writer.WriteLine($"return {RequestInfoVarName};"); } - private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"{property.Name.ToFirstCharacterLowerCase()}"; + private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"{property.Name}"; private void WriteSerializerBody(CodeClass parentClass, CodeMethod method, LanguageWriter writer, bool inherits) { if (parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForUnionType) @@ -613,7 +611,7 @@ private void WriteSerializerBodyForUnionModel(CodeClass parentClass, CodeMethod .ToArray(); foreach (var otherProp in otherProps) { - writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (this.{otherProp.Getter!.Name.ToFirstCharacterLowerCase()}() != null) {{"); + writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (this.{otherProp.Getter!.Name}() != null) {{"); WriteSerializationMethodCall(otherProp, method, writer, "null"); writer.DecreaseIndent(); if (!includeElse) @@ -634,7 +632,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Code .ToArray(); foreach (var otherProp in otherProps) { - writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (this.{otherProp.Getter!.Name.ToFirstCharacterLowerCase()}() != null) {{"); + writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if (this.{otherProp.Getter!.Name}() != null) {{"); WriteSerializationMethodCall(otherProp, method, writer, "null"); writer.DecreaseIndent(); if (!includeElse) @@ -652,7 +650,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Code } var propertiesNames = complexProperties .Where(static x => x.Getter != null) - .Select(static x => $"this.{x.Getter!.Name.ToFirstCharacterLowerCase()}()") + .Select(static x => $"this.{x.Getter!.Name}()") .OrderBy(static x => x) .Aggregate(static (x, y) => $"{x}, {y}"); WriteSerializationMethodCall(complexProperties.First(), method, writer, "null", propertiesNames); @@ -676,42 +674,55 @@ private void WriteSerializerBodyForInheritedModel(CodeMethod method, bool inheri private void WriteSerializationMethodCall(CodeProperty otherProp, CodeMethod method, LanguageWriter writer, string serializationKey, string? dataToSerialize = default) { if (string.IsNullOrEmpty(dataToSerialize)) - dataToSerialize = $"this.{(otherProp.Getter?.Name?.ToFirstCharacterLowerCase() is string gName && !string.IsNullOrEmpty(gName) ? gName : "get" + otherProp.Name.ToFirstCharacterUpperCase())}()"; + dataToSerialize = $"this.{(otherProp.Getter?.Name is string gName && !string.IsNullOrEmpty(gName) ? gName : "get" + otherProp.Name)}()"; writer.WriteLine($"writer.{GetSerializationMethodName(otherProp.Type, method)}({serializationKey}, {dataToSerialize});"); } private static readonly BaseCodeParameterOrderComparer parameterOrderComparer = new(); - private void WriteMethodPrototype(CodeMethod code, LanguageWriter writer, string returnType) + private string GetFinalReturnType(CodeMethod code, string returnType) { - var accessModifier = conventions.GetAccessModifier(code.Access); + var voidType = code.IsAsync ? "Void" : "void"; var returnTypeAsyncPrefix = code.IsAsync ? "java.util.concurrent.CompletableFuture<" : string.Empty; var returnTypeAsyncSuffix = code.IsAsync ? ">" : string.Empty; + var reType = returnType.Equals("void", StringComparison.OrdinalIgnoreCase) ? voidType : returnType; + var collectionCorrectedReturnType = code.ReturnType.IsArray && code.IsOfKind(CodeMethodKind.RequestExecutor) ? + $"Iterable<{returnType.StripArraySuffix()}>" : + reType; + var isConstructor = code.IsOfKind(CodeMethodKind.Constructor, CodeMethodKind.ClientConstructor, CodeMethodKind.RawUrlConstructor); + var finalReturnType = isConstructor ? string.Empty : $"{returnTypeAsyncPrefix}{collectionCorrectedReturnType}{returnTypeAsyncSuffix}"; + return finalReturnType.Trim(); + } + private void WriteMethodPrototype(CodeMethod code, LanguageWriter writer, string returnType) + { + var accessModifier = conventions.GetAccessModifier(code.Access); var isConstructor = code.IsOfKind(CodeMethodKind.Constructor, CodeMethodKind.ClientConstructor, CodeMethodKind.RawUrlConstructor); var methodName = code.Kind switch { - _ when isConstructor && code.Parent != null => code.Parent.Name.ToFirstCharacterUpperCase(), - _ => code.Name.ToFirstCharacterLowerCase() + _ when isConstructor && code.Parent != null => code.Parent.Name, + _ => code.Name }; var parameters = string.Join(", ", code.Parameters.OrderBy(static x => x, parameterOrderComparer).Select(p => conventions.GetParameterSignature(p, code))); + var reType = returnType.Equals("void", StringComparison.OrdinalIgnoreCase) ? "void" : returnType; var collectionCorrectedReturnType = code.ReturnType.IsArray && code.IsOfKind(CodeMethodKind.RequestExecutor) ? $"Iterable<{returnType.StripArraySuffix()}>" : - returnType; - var finalReturnType = isConstructor ? string.Empty : $" {returnTypeAsyncPrefix}{collectionCorrectedReturnType}{returnTypeAsyncSuffix}"; + reType; var staticModifier = code.IsStatic ? " static" : string.Empty; conventions.WriteDeprecatedAnnotation(code, writer); if (code.Kind is CodeMethodKind.ErrorMessageOverride) { writer.WriteLine($"@Override"); } - writer.WriteLine($"{accessModifier}{staticModifier}{finalReturnType} {methodName}({parameters}) {{"); + if (returnType.Length > 0) + returnType = $" {returnType}"; + writer.WriteLine($"{accessModifier}{staticModifier}{returnType} {methodName}({parameters}) {{"); } - private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer, string returnType) + private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer, string baseReturnType, string finalReturnType) { - var returnVoid = returnType.Equals("void", StringComparison.OrdinalIgnoreCase); + var returnVoid = baseReturnType.Equals("void", StringComparison.OrdinalIgnoreCase); // Void returns, this includes constructors, should not have a return statement in the JavaDocs. var returnRemark = returnVoid ? string.Empty : (code.IsAsync switch { - true => $"@return a CompletableFuture of {code.ReturnType.Name}", - false => $"@return a {code.ReturnType.Name}", + true => $"@return a CompletableFuture of {baseReturnType}", + false => $"@return a {finalReturnType}", }); conventions.WriteLongDescription(code, writer, @@ -733,7 +744,7 @@ private string GetDeserializationMethodName(CodeTypeBase propType, CodeMethod me if (currentType.TypeDefinition == null) return $"getCollectionOfPrimitiveValues({propertyType.ToFirstCharacterUpperCase()}.class)"; else if (currentType.TypeDefinition is CodeEnum enumType) - return $"getCollectionOfEnumValues({enumType.Name.ToFirstCharacterUpperCase()}.class)"; + return $"getCollectionOfEnumValues({enumType.Name}.class)"; else return $"getCollectionOfObjectValues({propertyType.ToFirstCharacterUpperCase()}::{FactoryMethodName})"; if (currentType.TypeDefinition is CodeEnum currentEnum) diff --git a/src/Kiota.Builder/Writers/Java/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Java/CodePropertyWriter.cs index e72a95a031..8fd03c757e 100644 --- a/src/Kiota.Builder/Writers/Java/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodePropertyWriter.cs @@ -23,7 +23,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w throw new InvalidOperationException("Error message overrides are implemented with methods in Java."); case CodePropertyKind.RequestBuilder: writer.WriteLine("@jakarta.annotation.Nonnull"); - writer.StartBlock($"{conventions.GetAccessModifier(codeElement.Access)} {returnType} {codeElement.Name.ToFirstCharacterLowerCase()}() {{"); + writer.StartBlock($"{conventions.GetAccessModifier(codeElement.Access)} {returnType} {codeElement.Name}() {{"); conventions.AddRequestBuilderBody(parentClass, returnType, writer); writer.CloseBlock(); break; @@ -41,7 +41,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w returnType = $"EnumSet<{returnType}>"; if (codeElement.Access != AccessModifier.Private) writer.WriteLine(codeElement.Type.IsNullable ? "@jakarta.annotation.Nullable" : "@jakarta.annotation.Nonnull"); - writer.WriteLine($"{conventions.GetAccessModifier(codeElement.Access)} {returnType} {codeElement.NamePrefix}{codeElement.Name.ToFirstCharacterLowerCase()}{defaultValue};"); + writer.WriteLine($"{conventions.GetAccessModifier(codeElement.Access)} {returnType} {codeElement.NamePrefix}{codeElement.Name}{defaultValue};"); break; } diff --git a/src/Kiota.Builder/Writers/Java/JavaConventionService.cs b/src/Kiota.Builder/Writers/Java/JavaConventionService.cs index 0108ad4b87..177b8c3e25 100644 --- a/src/Kiota.Builder/Writers/Java/JavaConventionService.cs +++ b/src/Kiota.Builder/Writers/Java/JavaConventionService.cs @@ -39,7 +39,7 @@ public override string GetParameterSignature(CodeParameter parameter, CodeElemen var parameterType = GetTypeString(parameter.Type, targetElement); if (parameter.Type is CodeType { TypeDefinition: CodeEnum { Flags: true }, IsCollection: false }) parameterType = $"EnumSet<{parameterType}>"; - return $"{nullAnnotation}final {parameterType} {parameter.Name.ToFirstCharacterLowerCase()}"; + return $"{nullAnnotation}final {parameterType} {parameter.Name}"; } public override string GetTypeString(CodeTypeBase code, CodeElement targetElement, bool includeCollectionInformation = true, LanguageWriter? writer = null) @@ -83,14 +83,14 @@ public override string TranslateType(CodeType type) ArgumentNullException.ThrowIfNull(type); return type.Name switch { - "int64" => "Long", + "Int64" => "Long", "sbyte" => "Short", "decimal" => "BigDecimal", "void" or "boolean" when !type.IsNullable => type.Name, //little casing hack "binary" or "base64" or "base64url" => "byte[]", "Guid" => "UUID", _ when type.Name.Contains('.', StringComparison.OrdinalIgnoreCase) => type.Name, // casing - _ => type.Name.ToFirstCharacterUpperCase() is string typeName && !string.IsNullOrEmpty(typeName) ? typeName : "Object", + _ => type.Name is string typeName && !string.IsNullOrEmpty(typeName) ? typeName : "Object", }; } public override void WriteShortDescription(string description, LanguageWriter writer) @@ -133,7 +133,7 @@ internal void AddRequestBuilderBody(CodeClass parentClass, string returnType, La var pathParametersProperty = parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters); var requestAdapterProp = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter); var urlTemplateParams = string.IsNullOrEmpty(urlTemplateVarName) ? pathParametersProperty?.Name : urlTemplateVarName; - var pathParametersSuffix = !(pathParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", pathParameters.Select(x => $"{x.Name.ToFirstCharacterLowerCase()}"))}"; + var pathParametersSuffix = !(pathParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", pathParameters.Select(x => $"{x.Name}"))}"; writer.WriteLines($"return new {returnType}({urlTemplateParams}, {requestAdapterProp?.Name}{pathParametersSuffix});"); } public override string TempDictionaryVarName => "urlTplParams"; From 6b43f14f39ebcac2a1eab4129c9d205e9464ab14 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Thu, 7 Sep 2023 18:52:29 +0100 Subject: [PATCH 2/9] minor cleanup --- src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index ee43d355bc..c1449e3d39 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -137,9 +137,6 @@ protected static void ReplacePropertyNames(CodeElement current, HashSet PROPERTY " + currentProperty1.Name + " " + currentProperty1.Kind + " - " + currentProperty1.ExistsInBaseType + " " + current.Parent); - if (current is CodeProperty currentProperty && !currentProperty.ExistsInBaseType && propertyKindsToReplace!.Contains(currentProperty.Kind) && From f958705f93200b237c1a2e1f1cb5e095cb7dde60 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Mon, 11 Sep 2023 11:23:44 +0100 Subject: [PATCH 3/9] twitter api passes --- src/Kiota.Builder/KiotaBuilder.cs | 14 +++++------ src/Kiota.Builder/Refiners/CSharpRefiner.cs | 1 + src/Kiota.Builder/Refiners/CliRefiner.cs | 3 ++- .../Refiners/CommonLanguageRefiner.cs | 23 +++++++++++-------- src/Kiota.Builder/Refiners/GoRefiner.cs | 1 + src/Kiota.Builder/Refiners/JavaRefiner.cs | 15 ++++++++++++ src/Kiota.Builder/Refiners/PhpRefiner.cs | 1 + src/Kiota.Builder/Refiners/RubyRefiner.cs | 3 ++- src/Kiota.Builder/Refiners/SwiftRefiner.cs | 3 ++- 9 files changed, 44 insertions(+), 20 deletions(-) diff --git a/src/Kiota.Builder/KiotaBuilder.cs b/src/Kiota.Builder/KiotaBuilder.cs index 9c64aa8cb9..710eebfa38 100644 --- a/src/Kiota.Builder/KiotaBuilder.cs +++ b/src/Kiota.Builder/KiotaBuilder.cs @@ -1839,7 +1839,7 @@ private CodeClass AddModelClass(OpenApiUrlTreeNode currentNode, OpenApiSchema sc // Add the class to the namespace after the serialization members // as other threads looking for the existence of the class may find the class but the additional data/backing store properties may not be fully populated causing duplication var includeAdditionalDataProperties = config.IncludeAdditionalData && schema.AdditionalPropertiesAllowed; - AddSerializationMembers(newClassStub, includeAdditionalDataProperties, config.UsesBackingStore); + AddSerializationMembers(newClassStub, includeAdditionalDataProperties, config.UsesBackingStore, static s => s); var newClass = currentNamespace.AddClass(newClassStub).First(); var lifecycle = classLifecycles.GetOrAdd(currentNamespace.Name + "." + declarationName, static n => new()); @@ -1870,7 +1870,7 @@ private CodeClass AddModelClass(OpenApiUrlTreeNode currentNode, OpenApiSchema sc type.TypeDefinition is CodeClass definition && definition.DerivesFrom(newClass)); // only the mappings that derive from the current class - AddDiscriminatorMethod(newClass, schema.GetDiscriminatorPropertyName(), mappings); + AddDiscriminatorMethod(newClass, schema.GetDiscriminatorPropertyName(), mappings, static s => s); return newClass; } private IEnumerable> GetDiscriminatorMappings(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, CodeNamespace currentNamespace, CodeClass? baseClass) @@ -2012,11 +2012,11 @@ private void InitializeInheritanceIndex() { openApiDocument?.InitializeInheritanceIndex(inheritanceIndex); } - internal static void AddDiscriminatorMethod(CodeClass newClass, string discriminatorPropertyName, IEnumerable> discriminatorMappings) + internal static void AddDiscriminatorMethod(CodeClass newClass, string discriminatorPropertyName, IEnumerable> discriminatorMappings, Func refineMethodName) { var factoryMethod = new CodeMethod { - Name = "CreateFromDiscriminatorValue", + Name = refineMethodName("CreateFromDiscriminatorValue"), Documentation = new() { Description = "Creates a new instance of the appropriate class based on discriminator value", @@ -2107,14 +2107,14 @@ private Dictionary CollectAllProperties(OpenApiSchema sch internal const string BackedModelInterface = "IBackedModel"; private const string ParseNodeInterface = "IParseNode"; internal const string AdditionalHolderInterface = "IAdditionalDataHolder"; - internal static void AddSerializationMembers(CodeClass model, bool includeAdditionalProperties, bool usesBackingStore) + internal static void AddSerializationMembers(CodeClass model, bool includeAdditionalProperties, bool usesBackingStore, Func refineMethodName) { var serializationPropsType = $"IDictionary>"; if (!model.ContainsMember(FieldDeserializersMethodName)) { var deserializeProp = new CodeMethod { - Name = FieldDeserializersMethodName, + Name = refineMethodName(FieldDeserializersMethodName), Kind = CodeMethodKind.Deserializer, Access = AccessModifier.Public, Documentation = new() @@ -2136,7 +2136,7 @@ internal static void AddSerializationMembers(CodeClass model, bool includeAdditi { var serializeMethod = new CodeMethod { - Name = SerializeMethodName, + Name = refineMethodName(SerializeMethodName), Kind = CodeMethodKind.Serializer, IsAsync = false, Documentation = new() diff --git a/src/Kiota.Builder/Refiners/CSharpRefiner.cs b/src/Kiota.Builder/Refiners/CSharpRefiner.cs index 5689d654c1..308fe9b6a7 100644 --- a/src/Kiota.Builder/Refiners/CSharpRefiner.cs +++ b/src/Kiota.Builder/Refiners/CSharpRefiner.cs @@ -51,6 +51,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance MoveClassesWithNamespaceNamesUnderNamespace(generatedCode); ConvertUnionTypesToWrapper(generatedCode, _configuration.UsesBackingStore, + static s => s, true, AbstractionsNamespaceName, "IComposedTypeWrapper" diff --git a/src/Kiota.Builder/Refiners/CliRefiner.cs b/src/Kiota.Builder/Refiners/CliRefiner.cs index 8fc91ee402..053cc3fa24 100644 --- a/src/Kiota.Builder/Refiners/CliRefiner.cs +++ b/src/Kiota.Builder/Refiners/CliRefiner.cs @@ -53,7 +53,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance cancellationToken.ThrowIfCancellationRequested(); MoveClassesWithNamespaceNamesUnderNamespace(generatedCode); ConvertUnionTypesToWrapper(generatedCode, - _configuration.UsesBackingStore + _configuration.UsesBackingStore, + static s => s ); AddPropertiesAndMethodTypesImports(generatedCode, false, false, false); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index c1449e3d39..c8ca090abb 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -442,30 +442,33 @@ protected static void ReplaceBinaryByNativeType(CodeElement currentElement, stri } CrawlTree(currentElement, c => ReplaceBinaryByNativeType(c, symbol, ns, addDeclaration, isNullable)); } - protected static void ConvertUnionTypesToWrapper(CodeElement currentElement, bool usesBackingStore, bool supportInnerClasses = true, string markerInterfaceNamespace = "", string markerInterfaceName = "", string markerMethodName = "") + protected static void ConvertUnionTypesToWrapper(CodeElement currentElement, bool usesBackingStore, Func refineMethodName, bool supportInnerClasses = true, string markerInterfaceNamespace = "", string markerInterfaceName = "", string markerMethodName = "") { ArgumentNullException.ThrowIfNull(currentElement); + ArgumentNullException.ThrowIfNull(refineMethodName); if (currentElement.Parent is CodeClass parentClass) { if (currentElement is CodeMethod currentMethod) { + currentMethod.Name = refineMethodName(currentMethod.Name); + if (currentMethod.ReturnType is CodeComposedTypeBase currentUnionType) - currentMethod.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); + currentMethod.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); if (currentMethod.Parameters.Any(static x => x.Type is CodeComposedTypeBase)) foreach (var currentParameter in currentMethod.Parameters.Where(static x => x.Type is CodeComposedTypeBase)) - currentParameter.Type = ConvertComposedTypeToWrapper(parentClass, (CodeComposedTypeBase)currentParameter.Type, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); + currentParameter.Type = ConvertComposedTypeToWrapper(parentClass, (CodeComposedTypeBase)currentParameter.Type, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); if (currentMethod.ErrorMappings.Select(static x => x.Value).OfType().Any()) foreach (var errorUnionType in currentMethod.ErrorMappings.Select(static x => x.Value).OfType()) - currentMethod.ReplaceErrorMapping(errorUnionType, ConvertComposedTypeToWrapper(parentClass, errorUnionType, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName)); + currentMethod.ReplaceErrorMapping(errorUnionType, ConvertComposedTypeToWrapper(parentClass, errorUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName)); } else if (currentElement is CodeIndexer currentIndexer && currentIndexer.ReturnType is CodeComposedTypeBase currentUnionType) - currentIndexer.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); + currentIndexer.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); else if (currentElement is CodeProperty currentProperty && currentProperty.Type is CodeComposedTypeBase currentPropUnionType) - currentProperty.Type = ConvertComposedTypeToWrapper(parentClass, currentPropUnionType, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); + currentProperty.Type = ConvertComposedTypeToWrapper(parentClass, currentPropUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName); } - CrawlTree(currentElement, x => ConvertUnionTypesToWrapper(x, usesBackingStore, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName)); + CrawlTree(currentElement, x => ConvertUnionTypesToWrapper(x, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName)); } - private static CodeTypeBase ConvertComposedTypeToWrapper(CodeClass codeClass, CodeComposedTypeBase codeComposedType, bool usesBackingStore, bool supportsInnerClasses, string markerInterfaceNamespace, string markerInterfaceName, string markerMethodName) + private static CodeTypeBase ConvertComposedTypeToWrapper(CodeClass codeClass, CodeComposedTypeBase codeComposedType, bool usesBackingStore, Func refineMethodName, bool supportsInnerClasses, string markerInterfaceNamespace, string markerInterfaceName, string markerMethodName) { ArgumentNullException.ThrowIfNull(codeClass); ArgumentNullException.ThrowIfNull(codeComposedType); @@ -530,7 +533,7 @@ private static CodeTypeBase ConvertComposedTypeToWrapper(CodeClass codeClass, Co if (codeComposedType.Types.All(static x => x.TypeDefinition is CodeClass targetClass && targetClass.IsOfKind(CodeClassKind.Model) || x.TypeDefinition is CodeEnum || x.TypeDefinition is null)) { - KiotaBuilder.AddSerializationMembers(newClass, false, usesBackingStore); + KiotaBuilder.AddSerializationMembers(newClass, false, usesBackingStore, refineMethodName); newClass.Kind = CodeClassKind.Model; } newClass.OriginalComposedType = codeComposedType; @@ -571,7 +574,7 @@ private static CodeTypeBase ConvertComposedTypeToWrapper(CodeClass codeClass, Co }); } // Add the discriminator function to the wrapper as it will be referenced. - KiotaBuilder.AddDiscriminatorMethod(newClass, codeComposedType.DiscriminatorInformation.DiscriminatorPropertyName, codeComposedType.DiscriminatorInformation.DiscriminatorMappings); + KiotaBuilder.AddDiscriminatorMethod(newClass, codeComposedType.DiscriminatorInformation.DiscriminatorPropertyName, codeComposedType.DiscriminatorInformation.DiscriminatorMappings, refineMethodName); return new CodeType { Name = newClass.Name, diff --git a/src/Kiota.Builder/Refiners/GoRefiner.cs b/src/Kiota.Builder/Refiners/GoRefiner.cs index 80ed71ac75..4a183e16ff 100644 --- a/src/Kiota.Builder/Refiners/GoRefiner.cs +++ b/src/Kiota.Builder/Refiners/GoRefiner.cs @@ -53,6 +53,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance ConvertUnionTypesToWrapper( generatedCode, _configuration.UsesBackingStore, + static s => s, true, string.Empty, string.Empty, diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index f6a7b33a24..3dd7a56e83 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -62,6 +62,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance RemoveCancellationParameter(generatedCode); ConvertUnionTypesToWrapper(generatedCode, _configuration.UsesBackingStore, + s => s.ToFirstCharacterLowerCase(), true, SerializationNamespaceName, "ComposedTypeWrapper" @@ -265,6 +266,20 @@ private static void CorrectCommonNames(CodeElement currentElement) { i.IndexParameter.Name = i.IndexParameter.Name.ToFirstCharacterLowerCase(); } + else if (currentElement is CodeEnum e) + { + foreach (var option in e.Options) + { + if (!string.IsNullOrEmpty(option.Name) && Char.IsLower(option.Name[0])) + { + if (string.IsNullOrEmpty(option.SerializationName)) + { + option.SerializationName = option.Name; + } + option.Name = option.Name.ToFirstCharacterUpperCase(); + } + } + } CrawlTree(currentElement, element => CorrectCommonNames(element)); } diff --git a/src/Kiota.Builder/Refiners/PhpRefiner.cs b/src/Kiota.Builder/Refiners/PhpRefiner.cs index 679b1a6b14..4850e151fa 100644 --- a/src/Kiota.Builder/Refiners/PhpRefiner.cs +++ b/src/Kiota.Builder/Refiners/PhpRefiner.cs @@ -43,6 +43,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance RemoveCancellationParameter(generatedCode); ConvertUnionTypesToWrapper(generatedCode, _configuration.UsesBackingStore, + static s => s, false); ReplaceReservedNames(generatedCode, new PhpReservedNamesProvider(), reservedWord => $"Escaped{reservedWord.ToFirstCharacterUpperCase()}", new HashSet { typeof(CodeEnumOption) }); AddQueryParameterFactoryMethod(generatedCode); diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 156b29b243..555e457adb 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -56,7 +56,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance AddPropertiesAndMethodTypesImports(generatedCode, false, false, true); RemoveCancellationParameter(generatedCode); ConvertUnionTypesToWrapper(generatedCode, - _configuration.UsesBackingStore + _configuration.UsesBackingStore, + static s => s ); cancellationToken.ThrowIfCancellationRequested(); AddParsableImplementsForModelClasses(generatedCode, "MicrosoftKiotaAbstractions::Parsable"); diff --git a/src/Kiota.Builder/Refiners/SwiftRefiner.cs b/src/Kiota.Builder/Refiners/SwiftRefiner.cs index 2aff3183de..18e31276de 100644 --- a/src/Kiota.Builder/Refiners/SwiftRefiner.cs +++ b/src/Kiota.Builder/Refiners/SwiftRefiner.cs @@ -32,7 +32,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance RemoveCancellationParameter(generatedCode); ConvertUnionTypesToWrapper( generatedCode, - _configuration.UsesBackingStore + _configuration.UsesBackingStore, + static s => s ); cancellationToken.ThrowIfCancellationRequested(); AddPropertiesAndMethodTypesImports( From 9787edb04914442e357f3cca5c7d198e7d0b2e61 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Mon, 11 Sep 2023 14:26:13 +0100 Subject: [PATCH 4/9] more --- .../Refiners/CommonLanguageRefiner.cs | 2 +- src/Kiota.Builder/Refiners/JavaRefiner.cs | 2 - .../Writers/Java/CodeMethodWriter.cs | 8 +- .../Refiners/CSharpLanguageRefinerTests.cs | 2 +- .../Refiners/JavaLanguageRefinerTests.cs | 6 +- .../Writers/Java/CodeEnumWriterTests.cs | 2 +- .../Writers/Java/CodeMethodWriterTests.cs | 158 +++++++++--------- 7 files changed, 89 insertions(+), 91 deletions(-) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index c8ca090abb..8a37d3a04e 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -146,7 +146,7 @@ current.Parent is CodeClass parentClass && var refinedName = refineAccessorName(currentProperty.Name); if (!refinedName.Equals(currentProperty.Name, StringComparison.Ordinal) && - !parentClass.Properties.Any(property => !property.Name.Equals(property.Name, StringComparison.Ordinal) && refinedName.Equals(property.Name, StringComparison.OrdinalIgnoreCase)))// ensure the refinement won't generate a duplicate + !parentClass.Properties.Any(property => !property.Name.Equals(property.Name, StringComparison.Ordinal) && refinedName.Equals(property.Name, StringComparison.Ordinal)))// ensure the refinement won't generate a duplicate { if (string.IsNullOrEmpty(currentProperty.SerializationName)) currentProperty.SerializationName = currentProperty.Name; diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index 3dd7a56e83..feb6ba62e2 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -8,7 +7,6 @@ using Kiota.Builder.Configuration; using Kiota.Builder.Extensions; using Kiota.Builder.Writers.Java; -using Microsoft.VisualBasic; namespace Kiota.Builder.Refiners; public class JavaRefiner : CommonLanguageRefiner, ILanguageRefiner diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index 51e171a286..6b59474f7a 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -348,7 +348,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho .Where(static x => x.Type is not CodeType propType || propType.TypeDefinition is not CodeClass propertyClass || propertyClass.OriginalComposedType is null) .OrderBy(static x => x.Name)) { - var setterName = propWithDefault.SetterFromCurrentOrBaseType?.Name is string sName && !string.IsNullOrEmpty(sName) ? sName : $"set{propWithDefault.Name}"; + var setterName = propWithDefault.SetterFromCurrentOrBaseType?.Name is string sName && !string.IsNullOrEmpty(sName) ? sName : $"set{propWithDefault.Name.ToFirstCharacterUpperCase()}"; var defaultValue = propWithDefault.DefaultValue; if (propWithDefault.Type is CodeType propertyType && propertyType.TypeDefinition is CodeEnum enumDefinition) { @@ -375,7 +375,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho private static void WriteSetterBody(CodeMethod codeElement, LanguageWriter writer, CodeClass parentClass) { if (parentClass.GetBackingStoreProperty() is CodeProperty backingStore) - writer.WriteLine($"this.get{backingStore.Name}().set(\"{codeElement.AccessedProperty?.Name}\", value);"); + writer.WriteLine($"this.get{backingStore.Name.ToFirstCharacterUpperCase()}().set(\"{codeElement.AccessedProperty?.Name}\", value);"); else { string value = "PeriodAndDuration".Equals(codeElement.AccessedProperty?.Type?.Name, StringComparison.OrdinalIgnoreCase) ? "PeriodAndDuration.ofPeriodAndDuration(value);" : "value;"; @@ -396,12 +396,12 @@ private void WriteGetterBody(CodeMethod codeElement, LanguageWriter writer, Code writer.WriteLine($"{conventions.GetTypeString(codeElement.AccessedProperty.Type, codeElement)} value = this.{backingStore.NamePrefix}{backingStore.Name}\");"); writer.StartBlock("if(value == null) {"); writer.WriteLines($"value = {codeElement.AccessedProperty.DefaultValue};", - $"this.set{codeElement.AccessedProperty?.Name}(value);"); + $"this.set{codeElement.AccessedProperty?.Name.ToFirstCharacterUpperCase()}(value);"); writer.CloseBlock(); writer.WriteLine("return value;"); } else - writer.WriteLine($"return this.get{backingStore.Name}().get(\"{codeElement.AccessedProperty?.Name}\");"); + writer.WriteLine($"return this.get{backingStore.Name.ToFirstCharacterUpperCase()}().get(\"{codeElement.AccessedProperty?.Name}\");"); } private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer, string returnType) diff --git a/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs index fc69031a14..33099b3b28 100644 --- a/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs @@ -183,7 +183,7 @@ public async Task DoesNotEscapesReservedKeywordsForClassOrPropertyKind() // Assert Assert.Equal("break", model.Name); Assert.DoesNotContain("@", model.Name); // classname will be capitalized - Assert.Equal("alias", property.Name); + Assert.Equal("Alias", property.Name); Assert.DoesNotContain("@", property.Name); // classname will be capitalized } diff --git a/tests/Kiota.Builder.Tests/Refiners/JavaLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/JavaLanguageRefinerTests.cs index b81dc3a700..e81a45548d 100644 --- a/tests/Kiota.Builder.Tests/Refiners/JavaLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/JavaLanguageRefinerTests.cs @@ -21,11 +21,11 @@ public async Task DoesNotReplacesReservedEnumOptions() }).First(); var option = new CodeEnumOption { - Name = "break", // this a keyword + Name = "Void", // this a keyword }; model.AddOption(option); await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Java }, root); - Assert.Equal("break", option.Name); + Assert.Equal("Void", option.Name); Assert.Empty(option.SerializationName); } [Fact] @@ -436,7 +436,7 @@ public async Task NormalizeMethodTypesNames() method.AddParameter(nonNormalizedParam); method.AddParameter(normalizedParam); await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Java }, root); - Assert.Equal("foo_bar", method.Parameters.First().Type.Name); + Assert.Equal("Foo_bar", method.Parameters.First().Type.Name); Assert.Equal("FooBaz", method.Parameters.Last().Type.Name); } [Fact] diff --git a/tests/Kiota.Builder.Tests/Writers/Java/CodeEnumWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Java/CodeEnumWriterTests.cs index 352c999b09..a0b704cc89 100644 --- a/tests/Kiota.Builder.Tests/Writers/Java/CodeEnumWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Java/CodeEnumWriterTests.cs @@ -89,6 +89,6 @@ public void WritesEnumSerializationValue() currentEnum.AddOption(option); writer.Write(currentEnum); var result = tw.ToString(); - Assert.Contains($"Plus_1(\"+1\")", result); + Assert.Contains($"plus_1(\"+1\")", result); } } diff --git a/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs index 26cc6dd30e..4d30e430e9 100644 --- a/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs @@ -43,27 +43,27 @@ private void setup(bool withInheritance = false) { baseClass = root.AddClass(new CodeClass { - Name = "someParentClass", + Name = "SomeParentClass", }).First(); baseClass.AddProperty(new CodeProperty { Name = "definedInParent", Type = new CodeType { - Name = "string" + Name = "String" }, Kind = CodePropertyKind.Custom, }); } parentClass = new CodeClass { - Name = "parentClass" + Name = "ParentClass" }; if (withInheritance) { parentClass.StartBlock.Inherits = new CodeType { - Name = "someParentClass", + Name = "SomeParentClass", TypeDefinition = baseClass }; } @@ -105,7 +105,7 @@ private void AddRequestProperties() Kind = CodePropertyKind.PathParameters, Type = new CodeType { - Name = "string", + Name = "String", } }); parentClass.AddProperty(new CodeProperty @@ -114,7 +114,7 @@ private void AddRequestProperties() Kind = CodePropertyKind.UrlTemplate, Type = new CodeType { - Name = "string", + Name = "String", } }); } @@ -126,22 +126,22 @@ private void AddSerializationProperties() Kind = CodePropertyKind.AdditionalData, Type = new CodeType { - Name = "string" + Name = "String" }, Getter = new CodeMethod { - Name = "GetAdditionalData", + Name = "getAdditionalData", ReturnType = new CodeType { - Name = "string" + Name = "String" } }, Setter = new CodeMethod { - Name = "SetAdditionalData", + Name = "setAdditionalData", ReturnType = new CodeType { - Name = "string" + Name = "String" } } }); @@ -150,19 +150,19 @@ private void AddSerializationProperties() Name = "dummyProp", Type = new CodeType { - Name = "string" + Name = "String" }, Getter = new CodeMethod { - Name = "GetDummyProp", + Name = "getDummyProp", ReturnType = new CodeType { - Name = "string" + Name = "String" }, }, Setter = new CodeMethod { - Name = "SetDummyProp", + Name = "setDummyProp", ReturnType = new CodeType { Name = "void" @@ -175,7 +175,7 @@ private void AddSerializationProperties() Kind = CodePropertyKind.Custom, Type = new CodeType { - Name = "string" + Name = "String" } }); parentClass.AddProperty(new CodeProperty @@ -183,21 +183,21 @@ private void AddSerializationProperties() Name = "dummyColl", Type = new CodeType { - Name = "string", + Name = "String", CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array, }, Getter = new CodeMethod { - Name = "GetDummyColl", + Name = "getDummyColl", ReturnType = new CodeType { - Name = "string", + Name = "String", CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array, }, }, Setter = new CodeMethod { - Name = "SetDummyColl", + Name = "setDummyColl", ReturnType = new CodeType { Name = "void", @@ -218,16 +218,16 @@ private void AddSerializationProperties() }, Getter = new CodeMethod { - Name = "GetDummyComplexColl", + Name = "getDummyComplexColl", ReturnType = new CodeType { - Name = "string", + Name = "String", CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array, }, }, Setter = new CodeMethod { - Name = "SetDummyComplexColl", + Name = "setDummyComplexColl", ReturnType = new CodeType { Name = "void" @@ -247,15 +247,15 @@ private void AddSerializationProperties() }, Getter = new CodeMethod { - Name = "GetDummyEnumCollection", + Name = "getDummyEnumCollection", ReturnType = new CodeType { - Name = "string" + Name = "String" }, }, Setter = new CodeMethod { - Name = "SetDummyEnumCollection", + Name = "setDummyEnumCollection", ReturnType = new CodeType { Name = "void" @@ -301,7 +301,7 @@ private CodeClass AddUnionTypeWrapper() }; var sType = new CodeType { - Name = "string", + Name = "String", }; unionTypeWrapper.DiscriminatorInformation.AddDiscriminatorMapping("#kiota.complexType1", new CodeType { @@ -323,7 +323,7 @@ private CodeClass AddUnionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetComplexType1Value", + Name = "setComplexType1Value", ReturnType = new CodeType { Name = "void" @@ -332,7 +332,7 @@ private CodeClass AddUnionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetComplexType1Value", + Name = "getComplexType1Value", ReturnType = cType1, Kind = CodeMethodKind.Getter, } @@ -344,7 +344,7 @@ private CodeClass AddUnionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetComplexType2Value", + Name = "setComplexType2Value", ReturnType = new CodeType { Name = "void" @@ -353,7 +353,7 @@ private CodeClass AddUnionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetComplexType2Value", + Name = "getComplexType2Value", ReturnType = cType2, Kind = CodeMethodKind.Getter, } @@ -365,7 +365,7 @@ private CodeClass AddUnionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetStringValue", + Name = "setStringValue", ReturnType = new CodeType { Name = "void" @@ -374,7 +374,7 @@ private CodeClass AddUnionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetStringValue", + Name = "getStringValue", ReturnType = sType, Kind = CodeMethodKind.Getter, } @@ -444,7 +444,7 @@ private CodeClass AddIntersectionTypeWrapper() }); var sType = new CodeType { - Name = "string", + Name = "String", }; intersectionTypeWrapper.OriginalComposedType.AddType(cType1); intersectionTypeWrapper.OriginalComposedType.AddType(cType2); @@ -457,7 +457,7 @@ private CodeClass AddIntersectionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetComplexType1Value", + Name = "setComplexType1Value", ReturnType = new CodeType { Name = "void" @@ -466,7 +466,7 @@ private CodeClass AddIntersectionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetComplexType1Value", + Name = "getComplexType1Value", ReturnType = cType1, Kind = CodeMethodKind.Getter, } @@ -478,7 +478,7 @@ private CodeClass AddIntersectionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetComplexType2Value", + Name = "setComplexType2Value", ReturnType = new CodeType { Name = "void" @@ -487,7 +487,7 @@ private CodeClass AddIntersectionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetComplexType2Value", + Name = "getComplexType2Value", ReturnType = cType2, Kind = CodeMethodKind.Getter, } @@ -499,7 +499,7 @@ private CodeClass AddIntersectionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetComplexType3Value", + Name = "setComplexType3Value", ReturnType = new CodeType { Name = "void" @@ -508,7 +508,7 @@ private CodeClass AddIntersectionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetComplexType3Value", + Name = "getComplexType3Value", ReturnType = cType3, Kind = CodeMethodKind.Getter, } @@ -520,7 +520,7 @@ private CodeClass AddIntersectionTypeWrapper() Kind = CodePropertyKind.Custom, Setter = new CodeMethod { - Name = "SetStringValue", + Name = "setStringValue", ReturnType = new CodeType { Name = "void" @@ -529,7 +529,7 @@ private CodeClass AddIntersectionTypeWrapper() }, Getter = new CodeMethod { - Name = "GetStringValue", + Name = "getStringValue", ReturnType = sType, Kind = CodeMethodKind.Getter, } @@ -540,7 +540,7 @@ private void AddRequestBodyParameters(bool useComplexTypeForBody = false) { var stringType = new CodeType { - Name = "string", + Name = "String", }; var requestConfigClass = parentClass.AddInnerClass(new CodeClass { @@ -790,17 +790,17 @@ public void WritesModelFactoryBody() setup(); var parentModel = root.AddClass(new CodeClass { - Name = "parentModel", + Name = "ParentModel", Kind = CodeClassKind.Model, }).First(); var childModel = root.AddClass(new CodeClass { - Name = "childModel", + Name = "ChildModel", Kind = CodeClassKind.Model, }).First(); childModel.StartBlock.Inherits = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }; var factoryMethod = parentModel.AddMethod(new CodeMethod @@ -809,7 +809,7 @@ public void WritesModelFactoryBody() Kind = CodeMethodKind.Factory, ReturnType = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }, IsStatic = true, @@ -851,17 +851,17 @@ public void WritesModelSplitFactoryBody() setup(); var parentModel = root.AddClass(new CodeClass { - Name = "parentModel", + Name = "ParentModel", Kind = CodeClassKind.Model, }).First(); var childModel = root.AddClass(new CodeClass { - Name = "childModel", + Name = "ChildModel", Kind = CodeClassKind.Model, }).First(); childModel.StartBlock.Inherits = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }; var factoryMethod = parentModel.AddMethod(new CodeMethod @@ -870,7 +870,7 @@ public void WritesModelSplitFactoryBody() Kind = CodeMethodKind.Factory, ReturnType = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }, IsStatic = true, @@ -999,7 +999,7 @@ public void WritesModelSplitFactoryOverloadBody() Assert.DoesNotContain("if (mappingValueNode != null) {", result); Assert.DoesNotContain("final String mappingValue = mappingValueNode.getStringValue()", result); Assert.Contains("switch (value) {", result); - Assert.Contains("case \"#microsoft.graph.Foo535\": return new ChildModel();", result); + Assert.Contains("case \"#microsoft.graph.Foo535\": return new childModel();", result); Assert.DoesNotContain("final ParentModel factory_1_result = factory_1(mappingValue);", result); Assert.DoesNotContain("if (factory_1_result != null) {", result); Assert.DoesNotContain("return new ParentModel()", result); @@ -1049,12 +1049,12 @@ public void DoesntWriteFactorySwitchOnEmptyPropertyName() setup(); var parentModel = root.AddClass(new CodeClass { - Name = "parentModel", + Name = "ParentModel", Kind = CodeClassKind.Model, }).First(); var childModel = root.AddClass(new CodeClass { - Name = "childModel", + Name = "ChildModel", Kind = CodeClassKind.Model, }).First(); childModel.StartBlock.Inherits = new CodeType @@ -1068,14 +1068,14 @@ public void DoesntWriteFactorySwitchOnEmptyPropertyName() Kind = CodeMethodKind.Factory, ReturnType = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }, IsStatic = true, }).First(); parentModel.DiscriminatorInformation.AddDiscriminatorMapping("ns.childmodel", new CodeType { - Name = "childModel", + Name = "ChildModel", TypeDefinition = childModel, }); parentModel.DiscriminatorInformation.DiscriminatorPropertyName = string.Empty; @@ -1110,7 +1110,7 @@ public void DoesntWriteFactorySwitchOnEmptyMappings() setup(); var parentModel = root.AddClass(new CodeClass { - Name = "parentModel", + Name = "ParentModel", Kind = CodeClassKind.Model, }).First(); var factoryMethod = parentModel.AddMethod(new CodeMethod @@ -1119,7 +1119,7 @@ public void DoesntWriteFactorySwitchOnEmptyMappings() Kind = CodeMethodKind.Factory, ReturnType = new CodeType { - Name = "parentModel", + Name = "ParentModel", TypeDefinition = parentModel, }, IsStatic = true, @@ -1286,7 +1286,7 @@ public void WritesUnionDeSerializerBody() var wrapper = AddUnionTypeWrapper(); var deserializationMethod = wrapper.AddMethod(new CodeMethod { - Name = "GetFieldDeserializers", + Name = "getFieldDeserializers", Kind = CodeMethodKind.Deserializer, IsAsync = false, ReturnType = new CodeType @@ -1470,7 +1470,7 @@ public void WritesMethodAsyncDescription() Name = ParamName, Type = new CodeType { - Name = "string" + Name = "String" } }; method.AddParameter(parameter); @@ -1500,7 +1500,7 @@ public void WritesMethodSyncDescription() Name = ParamName, Type = new CodeType { - Name = "string" + Name = "String" } }; method.AddParameter(parameter); @@ -1526,7 +1526,7 @@ public void WritesMethodDescriptionLink() Name = ParamName, Type = new CodeType { - Name = "string" + Name = "String" } }; method.AddParameter(parameter); @@ -1614,7 +1614,7 @@ public void WritesIndexer() Name = "idx", ReturnType = new CodeType { - Name = "string" + Name = "String" }, IndexParameter = new() { @@ -1646,7 +1646,7 @@ public void WritesPathParameterRequestBuilder() Kind = CodeParameterKind.Path, Type = new CodeType { - Name = "string" + Name = "String" } }); writer.Write(method); @@ -1675,7 +1675,7 @@ public void WritesGetterToBackingStoreWithNonnullProperty() parentClass.GetGreatestGrandparent().AddBackingStoreProperty(); method.AccessedProperty.Type = new CodeType { - Name = "string", + Name = "String", IsNullable = false, }; var defaultValue = "someDefaultValue"; @@ -1776,7 +1776,7 @@ public void WritesConstructor() Kind = CodePropertyKind.Custom, Type = new CodeType { - Name = "string" + Name = "String" } }); AddRequestProperties(); @@ -1791,7 +1791,7 @@ public void WritesConstructor() }); writer.Write(method); var result = tw.ToString(); - Assert.Contains(parentClass.Name.ToFirstCharacterUpperCase(), result); + Assert.Contains(parentClass.Name, result); Assert.Contains($"this.set{propName.ToFirstCharacterUpperCase()}({defaultValue})", result); Assert.Contains("super", result); } @@ -1807,14 +1807,14 @@ public void WritesWithUrl() Kind = CodeParameterKind.RawUrl, Type = new CodeType { - Name = "string" + Name = "String" }, }); Assert.Throws(() => writer.Write(method)); AddRequestProperties(); writer.Write(method); var result = tw.ToString(); - Assert.Contains($"return new {parentClass.Name.ToFirstCharacterUpperCase()}", result); + Assert.Contains($"return new {parentClass.Name}", result); } [Fact] public void DoesNotWriteConstructorWithDefaultFromComposedType() @@ -1845,7 +1845,7 @@ public void DoesNotWriteConstructorWithDefaultFromComposedType() }); var sType = new CodeType { - Name = "string", + Name = "String", }; var arrayType = new CodeType { @@ -1856,7 +1856,7 @@ public void DoesNotWriteConstructorWithDefaultFromComposedType() writer.Write(method); var result = tw.ToString(); - Assert.Contains(parentClass.Name.ToFirstCharacterUpperCase(), result); + Assert.Contains(parentClass.Name, result); Assert.DoesNotContain(defaultValue, result);//ensure the composed type is not referenced } [Fact] @@ -1874,7 +1874,7 @@ public void WritesRawUrlConstructor() Kind = CodePropertyKind.Custom, Type = new CodeType { - Name = "string" + Name = "String" } }); AddRequestProperties(); @@ -1884,12 +1884,12 @@ public void WritesRawUrlConstructor() Kind = CodeParameterKind.RawUrl, Type = new CodeType { - Name = "string" + Name = "String" } }); writer.Write(method); var result = tw.ToString(); - Assert.Contains(parentClass.Name.ToFirstCharacterUpperCase(), result); + Assert.Contains(parentClass.Name, result); Assert.Contains($"this.set{propName.ToFirstCharacterUpperCase()}({defaultValue})", result); Assert.Contains("super", result); } @@ -1929,7 +1929,7 @@ public void WritesApiConstructor() method.SerializerModules = new() { "com.microsoft.kiota.serialization.Serializer" }; writer.Write(method); var result = tw.ToString(); - Assert.Contains(parentClass.Name.ToFirstCharacterUpperCase(), result); + Assert.Contains(parentClass.Name, result); Assert.Contains("registerDefaultSerializer", result); Assert.Contains("registerDefaultDeserializer", result); Assert.Contains($"put(\"baseurl\", core.getBaseUrl())", result); @@ -1985,7 +1985,7 @@ public async Task AccessorsTargetingEscapedPropertiesAreNotEscapedThemselves() model.AddProperty(new CodeProperty { Name = "short", - Type = new CodeType { Name = "string" }, + Type = new CodeType { Name = "String" }, Access = AccessModifier.Public, Kind = CodePropertyKind.Custom, }); @@ -2014,16 +2014,16 @@ public void DoesntWriteReadOnlyPropertiesInSerializerBody() AddSerializationProperties(); parentClass.AddProperty(new CodeProperty { - Name = "ReadOnlyProperty", + Name = "readOnlyProperty", ReadOnly = true, Type = new CodeType { - Name = "string", + Name = "String", }, }); writer.Write(method); var result = tw.ToString(); - Assert.DoesNotContain("ReadOnlyProperty", result); + Assert.DoesNotContain("readOnlyProperty", result); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] From 237a8ac538110fcad623a5afe965a85d3bd58643 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Mon, 11 Sep 2023 15:07:25 +0100 Subject: [PATCH 5/9] more fixes --- src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs | 3 ++- .../Refiners/CSharpLanguageRefinerTests.cs | 12 ++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index 8a37d3a04e..d792bd2817 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -146,7 +146,8 @@ current.Parent is CodeClass parentClass && var refinedName = refineAccessorName(currentProperty.Name); if (!refinedName.Equals(currentProperty.Name, StringComparison.Ordinal) && - !parentClass.Properties.Any(property => !property.Name.Equals(property.Name, StringComparison.Ordinal) && refinedName.Equals(property.Name, StringComparison.Ordinal)))// ensure the refinement won't generate a duplicate + !parentClass.Properties.Any(property => !currentProperty.Name.Equals(property.Name, StringComparison.Ordinal) && + refinedName.Equals(property.Name, StringComparison.OrdinalIgnoreCase)))// ensure the refinement won't generate a duplicate { if (string.IsNullOrEmpty(currentProperty.SerializationName)) currentProperty.SerializationName = currentProperty.Name; diff --git a/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs index 33099b3b28..6bb1989bea 100644 --- a/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/CSharpLanguageRefinerTests.cs @@ -122,7 +122,7 @@ public async Task InlineParentOnErrorClassesWhichAlreadyInherit() }; await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.CSharp }, root); - Assert.Contains(model.Properties, x => x.Name.Equals("otherProp")); + Assert.Contains(model.Properties, x => x.Name.Equals("OtherProp")); Assert.Contains(model.Methods, x => x.Name.Equals("otherMethod")); Assert.Contains(model.Usings, x => x.Name.Equals("otherNs")); } @@ -230,10 +230,10 @@ public async Task DoesNotEscapesReservedKeywordsForClassOrPropertyKindEnhanced() // Assert Assert.Equal("fileObject1", reservedModel.Name);// classes/models will be renamed if reserved without conflicts Assert.Equal("fileObject", reservedObjectModel.Name);// original stays the same - Assert.Equal("alias", property.Name);// property names don't bring issue in dotnet - Assert.Equal("file", secondProperty.Name);// property names don't bring issue in dotnet + Assert.Equal("Alias", property.Name);// property names don't bring issue in dotnet + Assert.Equal("File", secondProperty.Name);// property names don't bring issue in dotnet Assert.Equal("fileObject1", secondProperty.Type.Name);// property type was renamed - Assert.Equal("fileObject", thirdProperty.Name);// property names don't bring issue in dotnet + Assert.Equal("FileObject", thirdProperty.Name);// property names don't bring issue in dotnet Assert.Equal("fileObject", thirdProperty.Type.Name);// property type was renamed } @@ -494,7 +494,7 @@ public async Task DisambiguatePropertiesWithClassNames() } }).First(); await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.CSharp }, root); - Assert.Equal("modelProp", propToAdd.Name); + Assert.Equal("ModelProp", propToAdd.Name); Assert.Equal("model", propToAdd.SerializationName); } [Fact] @@ -530,7 +530,7 @@ public async Task AvoidsPropertyNameReplacementIfDuplicatedGenerated() } }).First(); await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.CSharp }, root); - Assert.Equal("summary", firstProperty.Name);// remains as is. No refinement needed + Assert.Equal("Summary", firstProperty.Name);// remains as is. No refinement needed Assert.Equal("_summary", secondProperty.Name);// No refinement as it will create a duplicate with firstProperty Assert.Equal("Replaced", thirdProperty.Name);// Base case. Proper refinements } From 48fb9c0053ec9b26c473a6b62214d6ddb29ed40a Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Mon, 11 Sep 2023 15:10:43 +0100 Subject: [PATCH 6/9] revert changes to compare script --- it/compare-generation.ps1 | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index 0c8ff32561..c8c40cf710 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -62,7 +62,7 @@ $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory Start-Process "$kiotaExec" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "$kiotaExec" -ArgumentList "generate --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") @@ -81,10 +81,8 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString1)) $HashString2 = (Get-ChildItem $tmpFolder2 -Recurse | where { ! $_.PSIsContainer } | Get-FileHash -Algorithm MD5).Hash | Out-String Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) -Write-Output "Folder Old: $tmpFolder1" -Write-Output "Folder New: $tmpFolder2" - -diff --color -r "$tmpFolder1" "$tmpFolder2" +Write-Output "Folder 1: $tmpFolder1" +Write-Output "Folder 2: $tmpFolder2" if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" From 43b91fdeea1ade43d6889380932f0db38fa62157 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Mon, 11 Sep 2023 15:24:03 +0100 Subject: [PATCH 7/9] Fix rebase issues --- src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs | 5 ++--- .../Writers/Java/CodeMethodWriterTests.cs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index 6b59474f7a..b26c9513ff 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -16,9 +16,6 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri ArgumentNullException.ThrowIfNull(writer); if (codeElement.Parent is not CodeClass parentClass) throw new InvalidOperationException("the parent of a method should be a class"); - var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement); - if (codeElement.ReturnType is CodeType { TypeDefinition: CodeEnum { Flags: true }, IsCollection: false }) - returnType = $"EnumSet<{returnType}>"; var baseReturnType = conventions.GetTypeString(codeElement.ReturnType, codeElement); var finalReturnType = GetFinalReturnType(codeElement, baseReturnType); WriteMethodDocumentation(codeElement, writer, baseReturnType, finalReturnType); @@ -681,6 +678,8 @@ private void WriteSerializationMethodCall(CodeProperty otherProp, CodeMethod met private string GetFinalReturnType(CodeMethod code, string returnType) { var voidType = code.IsAsync ? "Void" : "void"; + if (code.ReturnType is CodeType { TypeDefinition: CodeEnum { Flags: true }, IsCollection: false }) + returnType = $"EnumSet<{returnType}>"; var returnTypeAsyncPrefix = code.IsAsync ? "java.util.concurrent.CompletableFuture<" : string.Empty; var returnTypeAsyncSuffix = code.IsAsync ? ">" : string.Empty; var reType = returnType.Equals("void", StringComparison.OrdinalIgnoreCase) ? voidType : returnType; diff --git a/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs index 4d30e430e9..01078f7390 100644 --- a/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs @@ -2074,7 +2074,7 @@ public void WritesMessageOverrideOnPrimary() Kind = CodeMethodKind.ErrorMessageOverride, ReturnType = new CodeType { - Name = "string", + Name = "String", IsNullable = false, }, IsAsync = false, From 406363e4f564f1dbba945ba3fb69a09380b0fb7b Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Tue, 12 Sep 2023 14:54:04 +0100 Subject: [PATCH 8/9] final fix --- src/Kiota.Builder/Refiners/JavaRefiner.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index feb6ba62e2..33e63c41b7 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -141,7 +141,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance SplitLongDiscriminatorMethods(generatedCode); AddPrimaryErrorMessage(generatedCode, "getMessage", - () => new CodeType { Name = "string", IsNullable = false, IsExternal = true } + () => new CodeType { Name = "String", IsNullable = false, IsExternal = true } ); }, cancellationToken); } From 9042405f9a4031c14a14761f3d71724edb8475e7 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 20 Sep 2023 11:14:36 +0100 Subject: [PATCH 9/9] review --- src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs | 4 ++-- src/Kiota.Builder/Refiners/JavaRefiner.cs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index d792bd2817..553b727766 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -186,7 +186,7 @@ current.Parent is CodeClass parentClass && ReturnType = (CodeTypeBase)currentProperty.Type.Clone(), Documentation = new() { - Description = $"Gets the {currentProperty.Name} property value. {currentProperty.Documentation.Description}", + Description = $"Gets the {currentProperty.WireName} property value. {currentProperty.Documentation.Description}", }, AccessedProperty = currentProperty, Deprecation = currentProperty.Deprecation, @@ -200,7 +200,7 @@ current.Parent is CodeClass parentClass && Kind = CodeMethodKind.Setter, Documentation = new() { - Description = $"Sets the {currentProperty.Name} property value. {currentProperty.Documentation.Description}", + Description = $"Sets the {currentProperty.WireName} property value. {currentProperty.Documentation.Description}", }, AccessedProperty = currentProperty, ReturnType = new CodeType diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index 33e63c41b7..a520c844db 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -256,9 +256,10 @@ private static void AddEnumSetImport(CodeElement currentElement) private const string MultipartBodyClassName = "MultipartBody"; private static void CorrectCommonNames(CodeElement currentElement) { - if (currentElement is CodeMethod m) + if (currentElement is CodeMethod m && + currentElement.Parent is CodeClass parentClass) { - m.Name = m.Name.ToFirstCharacterLowerCase(); + parentClass.RenameChildElement(m.Name, m.Name.ToFirstCharacterLowerCase()); } else if (currentElement is CodeIndexer i) {