-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathUtils.cs
More file actions
392 lines (344 loc) · 17.1 KB
/
Utils.cs
File metadata and controls
392 lines (344 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Vocabularies;
using Microsoft.OpenApi.OData.Edm;
using Microsoft.OpenApi.OData.Vocabulary;
namespace Microsoft.OpenApi.OData.Common
{
/// <summary>
/// Utilities methods
/// </summary>
public static class Utils
{
/// <summary>
/// Get the term qualified name when using the type of <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">The type of the term.</typeparam>
/// <returns>The qualified name.</returns>
public static string? GetTermQualifiedName<T>()
{
object[] attributes = typeof(T).GetCustomAttributes(typeof(TermAttribute), false);
if (attributes == null || attributes.Length == 0)
{
return null;
}
TermAttribute term = (TermAttribute)attributes[0];
return term.QualifiedName;
}
/// <summary>
/// Upper the first character of the string.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The changed string.</returns>
public static string? UpperFirstChar(string? input)
{
if (input == null)
{
return input;
}
char first = char.ToUpper(input[0]);
return first + input.Substring(1);
}
/// <summary>
/// Get an unique name.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="set">The input set.</param>
/// <returns>The changed string.</returns>
public static string GetUniqueName(string input, HashSet<string> set)
{
if (!set.Contains(input))
{
set.Add(input);
return input;
}
int index = 1;
string newInput;
do
{
newInput = input + index.ToString();
index++;
}
while (set.Contains(newInput));
set.Add(newInput);
return newInput;
}
/// <summary>
/// Check the input argument whether its value is null or not.
/// </summary>
/// <typeparam name="T">The input value type.</typeparam>
/// <param name="value">The input value</param>
/// <param name="parameterName">The input parameter name.</param>
/// <returns>The input value.</returns>
internal static T CheckArgumentNull<T>(T value, string parameterName) where T : class
{
if (null == value)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
/// <summary>
/// Check the input string null or empty.
/// </summary>
/// <param name="value">The input string</param>
/// <param name="parameterName">The input parameter name.</param>
/// <returns>The input value.</returns>
internal static string CheckArgumentNullOrEmpty(string value, string parameterName)
{
if (String.IsNullOrEmpty(value))
{
throw Error.ArgumentNullOrEmpty(parameterName);
}
return value;
}
/// <summary>
/// Lowers the first character of the string.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The changed string.</returns>
internal static string ToFirstCharacterLowerCase(this string input)
=> string.IsNullOrEmpty(input) ? input : $"{char.ToLowerInvariant(input.FirstOrDefault())}{input.Substring(1)}";
/// <summary>
/// Gets the navigation path.
/// </summary>
/// <param name="path">The <see cref="ODataPath"/>.</param>
/// <param name="navigationPropertyName">Optional: The navigation property name.</param>
internal static string NavigationPropertyPath(this ODataPath path, string? navigationPropertyName = null)
{
string value = string.Join("/",
path.Segments.OfType<ODataNavigationPropertySegment>().Select(e => e.Identifier));
return navigationPropertyName == null ? value : $"{value}/{navigationPropertyName}";
}
/// <summary>
/// Adds a mapping of custom extension values against custom attribute values for a given element to the provided
/// extensions object.
/// </summary>
/// <param name="extensions">The target extensions object in which the mapped extensions and custom attribute
/// values will be added to.</param>
/// <param name="context">The OData context.</param>
/// <param name="element">The target element.</param>
internal static void AddCustomAttributesToExtensions(this IDictionary<string, IOpenApiExtension> extensions, ODataContext context, IEdmElement element)
{
if (extensions == null ||
context == null ||
element == null)
{
return;
}
Dictionary<string, string> attributesValueMap = GetCustomXMLAttributesValueMapping(context.Model, element, context.Settings.CustomXMLAttributesMapping);
if (attributesValueMap is not null && attributesValueMap.Count > 0)
{
foreach (var item in attributesValueMap)
{
extensions.TryAdd(item.Key, new JsonNodeExtension(item.Value));
}
}
}
/// <summary>
/// Correlates and retrieves custom attribute values for a given element in an Edm model
/// from a provided dictionary mapping of attribute names and extension names.
/// </summary>
/// <param name="model">The Edm model.</param>
/// <param name="element">The target element.</param>
/// <param name="customXMLAttributesMapping">The dictionary mapping of attribute names and extension names.</param>
/// <returns>A dictionary of extension names mapped to the custom attribute values.</returns>
private static Dictionary<string, string> GetCustomXMLAttributesValueMapping(IEdmModel model, IEdmElement element, Dictionary<string, string> customXMLAttributesMapping)
{
Dictionary<string, string> attributesValueMap = new();
if (customXMLAttributesMapping is not {Count:>0} ||
model == null ||
element == null)
{
return attributesValueMap;
}
foreach (var item in customXMLAttributesMapping)
{
string attributeName = item.Key.Split(':').Last(); // example, 'ags:IsHidden' --> 'IsHidden'
string extensionName = item.Value;
var customXMLAttribute = model.DirectValueAnnotationsManager.GetDirectValueAnnotations(element)?
.Where(x => x.Name.Equals(attributeName, StringComparison.OrdinalIgnoreCase))?
.FirstOrDefault()?.Value as EdmStringConstant;
var attributeValue = customXMLAttribute?.Value;
if (!string.IsNullOrEmpty(attributeValue))
{
attributesValueMap.TryAdd(extensionName, attributeValue);
}
}
return attributesValueMap;
}
/// <summary>
/// Checks whether the base type of an <see cref="IEdmStructuredType"/> is referenced as a type within the Edm model.
/// </summary>
/// <param name="model">The Edm model.</param>
/// <param name="baseType">The base type of the target <see cref="IEdmStructuredType"/>.</param>
/// <param name="structuredTypes">Optional: The IEnumerable of <see cref="IEdmStructuredType"/> to check against.</param>
/// <param name="actions">Optional: The IEnumerable of <see cref="IEdmAction"/> to check against.</param>
/// <returns>True if reference is found, otherwise False.</returns>
internal static bool IsBaseTypeReferencedAsTypeInModel(
this IEdmModel model,
IEdmStructuredType baseType,
IEnumerable<IEdmStructuredType>? structuredTypes = null,
IEnumerable<IEdmAction>? actions = null)
{
string baseTypeName = baseType.FullTypeName();
bool isBaseTypeEntity = Constants.EntityName.Equals(baseTypeName?.Split('.').Last(), StringComparison.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(baseTypeName) && !isBaseTypeEntity)
{
structuredTypes ??= model.GetAllElements()
.Where(static x => x.SchemaElementKind == EdmSchemaElementKind.TypeDefinition)
.Where(static y => !y.Name.Equals(Constants.EntityName, StringComparison.OrdinalIgnoreCase))
.OfType<IEdmStructuredType>();
actions ??= model.GetAllElements()
.Where(static x => x.SchemaElementKind == EdmSchemaElementKind.Action)
.OfType<IEdmAction>();
// Is base type referenced as a type in any property within a structured type
bool isReferencedInStructuredType = structuredTypes
.Any(x => x.DeclaredProperties.Where(y => y.Type.TypeKind() == EdmTypeKind.Entity ||
y.Type.TypeKind() == EdmTypeKind.Collection ||
y.Type.TypeKind() == EdmTypeKind.Complex)
.Any(z => z.Type.FullName().Equals(baseTypeName, StringComparison.OrdinalIgnoreCase)));
if (isReferencedInStructuredType) return true;
// Is base type referenced as a type in any parameter in an action
bool isReferencedInAction = actions.Any(x => x.Parameters.Any(x => x.Type.FullName().Equals(baseTypeName, StringComparison.OrdinalIgnoreCase)));
if (isReferencedInAction) return true;
// Recursively check the base type
if (baseType.BaseType is not null)
return model.IsBaseTypeReferencedAsTypeInModel(baseType.BaseType, structuredTypes, actions);
}
return false;
}
/// <summary>
/// Gets the entity type of the target <paramref name="segment"/>.
/// </summary>
/// <param name="segment">The target <see cref="ODataSegment"/>.</param>
/// <returns>The entity type of the target <paramref name="segment"/>.</returns>
internal static IEdmEntityType? EntityTypeFromPathSegment(this ODataSegment segment)
{
CheckArgumentNull(segment, nameof(segment));
switch (segment)
{
case ODataNavigationPropertySegment navPropSegment:
return navPropSegment.EntityType;
case ODataNavigationSourceSegment navSourceSegment when navSourceSegment.NavigationSource is IEdmEntitySet entitySet:
return entitySet.EntityType;
case ODataNavigationSourceSegment navSourceSegment when navSourceSegment.NavigationSource is IEdmSingleton singleton:
return singleton.EntityType;
case ODataKeySegment keySegment:
return keySegment.EntityType;
case ODataOperationSegment:
return segment.EntityTypeFromOperationSegment();
default:
return null;
}
}
/// <summary>
/// Gets the entity type of the <paramref name="segment"/>.
/// </summary>
/// <param name="segment">The target <see cref="ODataOperationSegment"/>.</param>
/// <returns>The entity type of the target <paramref name="segment"/>.</returns>
private static IEdmEntityType? EntityTypeFromOperationSegment(this ODataSegment segment)
{
CheckArgumentNull(segment, nameof(segment));
if (segment is ODataOperationSegment operationSegment &&
operationSegment.Operation?.Parameters.FirstOrDefault() is IEdmOperationParameter bindingParameter)
{
IEdmTypeReference bindingType = bindingParameter.Type;
if (bindingType.IsCollection())
{
bindingType = bindingType.AsCollection().ElementType();
}
return bindingType.AsEntity().EntityDefinition();
}
return null;
}
/// <summary>
/// Attempts to add the specified <paramref name="path"/> and <paramref name="pathItem"/> to the <paramref name="pathItems"/> dictionary.
/// </summary>
/// <param name="pathItems">The target dictionary.</param>
/// <param name="context">The OData context</param>
/// <param name="path">The key to be added.</param>
/// <param name="pathItem">The value to be added.</param>
/// <returns>true when the key and/or value are successfully added/updated to the dictionary;
/// false when the dictionary already contains the specified key, and nothing gets added.</returns>
internal static bool TryAddPath(this IDictionary<string, IOpenApiPathItem> pathItems,
ODataContext context,
ODataPath path,
OpenApiPathItem pathItem)
{
CheckArgumentNull(pathItems, nameof(pathItems));
CheckArgumentNull(context, nameof(context));
CheckArgumentNull(path, nameof(path));
CheckArgumentNull(pathItem, nameof(pathItem));
OpenApiConvertSettings settings = context.Settings.Clone();
settings.EnableKeyAsSegment = context.KeyAsSegment;
string pathName = path.PathTemplate ?? path.GetPathItemName(settings);
if (!pathItems.TryAdd(pathName, pathItem))
{
if (path.LastSegment is not ODataOperationSegment lastSegment)
{
Debug.WriteLine("Duplicate path: " + pathName);
return false;
}
int secondLastSegmentIndex = 2;
if (path.Count < secondLastSegmentIndex)
{
Debug.WriteLine($"Invalid path. Operation not bound to any entity. Path: {pathName}");
return false;
}
ODataSegment lastSecondSegment = path.Segments.ElementAt(path.Count - secondLastSegmentIndex);
var boundEntityType = lastSecondSegment?.EntityTypeFromPathSegment();
var operationEntityType = lastSegment.EntityTypeFromOperationSegment();
var derivedTypes = (operationEntityType != null)
? context.Model.FindAllDerivedTypes(operationEntityType)
: null;
if (derivedTypes?.Any() ?? false)
{
if (boundEntityType != null && boundEntityType == operationEntityType)
{
// The operation's binding type exactly matches the entity set's type,
// so this is a more specific overload than whatever was added first.
pathItems[pathName] = pathItem;
return true;
}
if (boundEntityType != null && !derivedTypes.Contains(boundEntityType))
{
Debug.WriteLine($"Duplicate paths present but entity type of binding parameter '{operationEntityType}' " +
$"is not the base type of the bound entity type '{boundEntityType}'. Path: {pathName}");
}
return false;
}
else
{
// Function bound to a derived type; what was added before was a function bound to a base type,
// update the existing dictionary entry.
pathItems[pathName] = pathItem;
}
}
return true;
}
/// <summary>
/// Strips off a prefix value from a string.
/// </summary>
/// <param name="value">The target string value.</param>
/// <param name="prefix">The prefix value to strip off.</param>
/// <returns>The value with the prefix stripped off.</returns>
internal static string StripNamespacePrefix(this string value, string prefix)
{
CheckArgumentNullOrEmpty(value, nameof(value));
CheckArgumentNullOrEmpty(prefix, nameof(prefix));
// Trim trailing '.' for uniformity
prefix = prefix.TrimEnd('.');
return value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
? value.Substring(prefix.Length).TrimStart('.')
: value;
}
}
}