0
# Utility Functions
1
2
Helper classes and utilities for schema analysis, string manipulation, version handling, and model processing used throughout the OpenAPI Generator framework.
3
4
## Model Utilities
5
6
### ModelUtils
7
8
Static utility methods for working with OpenAPI models and schemas.
9
10
```java { .api }
11
class ModelUtils {
12
// Schema type checking
13
public static boolean isObjectSchema(Schema schema);
14
public static boolean isComposedSchema(Schema schema); // oneOf/anyOf/allOf schemas
15
public static boolean isMapSchema(Schema schema);
16
public static boolean isArraySchema(Schema schema);
17
public static boolean isStringSchema(Schema schema);
18
public static boolean isIntegerSchema(Schema schema);
19
public static boolean isNumberSchema(Schema schema);
20
public static boolean isBooleanSchema(Schema schema);
21
public static boolean isNullType(Schema schema);
22
public static boolean isAnyType(Schema schema);
23
24
// Format-specific schema checking
25
public static boolean isDateSchema(Schema schema); // date format strings
26
public static boolean isDateTimeSchema(Schema schema); // date-time format strings
27
public static boolean isByteArraySchema(Schema schema); // byte format strings
28
public static boolean isBinarySchema(Schema schema); // binary format strings
29
public static boolean isFileSchema(Schema schema); // file upload schemas
30
public static boolean isUUIDSchema(Schema schema); // uuid format strings
31
public static boolean isEmailSchema(Schema schema); // email format strings
32
public static boolean isPasswordSchema(Schema schema); // password format strings
33
34
// Schema analysis and discovery
35
public static List<String> getAllUsedSchemas(OpenAPI openAPI); // Find all referenced schemas
36
public static List<String> getUnusedSchemas(OpenAPI openAPI); // Find unreferenced schemas
37
public static String getSimpleRef(String ref); // Extract name from $ref URL
38
public static Schema unaliasSchema(Schema schema, OpenAPI openAPI); // Resolve schema aliases/references
39
40
// Model processing utilities
41
public static CodegenModel getModelByName(final String name, final Map<String, ModelsMap> models);
42
public static boolean isGenerateAliasAsModel(); // Check alias-as-model setting
43
public static void setGenerateAliasAsModel(boolean value); // Configure alias-as-model behavior
44
}
45
```
46
47
## String Utilities
48
49
### StringUtils
50
51
String manipulation utilities for code generation naming conventions.
52
53
```java { .api }
54
class StringUtils {
55
// Case transformation
56
public static String camelize(String word); // Convert to camelCase
57
public static String camelize(String word, CamelizeOption camelizeOption); // With options
58
public static String underscore(String word); // Convert to snake_case
59
public static String dashize(String word); // Convert to dash-case
60
61
// Text escaping and sanitization
62
public static String escape(String input, Map<String, String> mapping,
63
Set<String> charactersToAllow, Set<String> charactersToEscape);
64
}
65
66
enum CamelizeOption {
67
LOWERCASE_FIRST_LETTER, // Start with lowercase letter
68
UPPERCASE_FIRST_LETTER // Start with uppercase letter (PascalCase)
69
}
70
```
71
72
## Version Handling
73
74
### SemVer
75
76
Semantic version handling and comparison utilities.
77
78
```java { .api }
79
class SemVer implements Comparable<SemVer> {
80
// Constructors
81
public SemVer(String version); // Parse version string (e.g., "1.2.3-alpha+build")
82
83
// Version component access
84
public int getMajor(); // Get major version number
85
public int getMinor(); // Get minor version number
86
public int getPatch(); // Get patch version number
87
public String getPrerelease(); // Get prerelease identifier (alpha, beta, etc.)
88
public String getBuild(); // Get build metadata
89
90
// Comparison methods
91
public int compareTo(SemVer other); // Standard comparison (-1, 0, 1)
92
public boolean isGreaterThan(SemVer other); // Check if this > other
93
public boolean isLessThan(SemVer other); // Check if this < other
94
public boolean isEquivalentTo(SemVer other); // Check if versions are equivalent
95
96
// String representation
97
public String getVersion(); // Get normalized version string
98
public String toString(); // String representation
99
}
100
```
101
102
## Usage Examples
103
104
### Schema Analysis Utilities
105
106
```java
107
public class SchemaProcessor {
108
109
public void processOpenAPIDocument(OpenAPI openAPI) {
110
// Find all schemas referenced in the document
111
List<String> usedSchemas = ModelUtils.getAllUsedSchemas(openAPI);
112
System.out.println("Referenced schemas: " + usedSchemas.size());
113
114
// Identify unused schemas for cleanup
115
List<String> unusedSchemas = ModelUtils.getUnusedSchemas(openAPI);
116
if (!unusedSchemas.isEmpty()) {
117
System.out.println("Unused schemas that could be removed: " + unusedSchemas);
118
}
119
120
// Process each schema in components
121
Map<String, Schema> schemas = openAPI.getComponents().getSchemas();
122
for (Map.Entry<String, Schema> entry : schemas.entrySet()) {
123
String schemaName = entry.getKey();
124
Schema schema = entry.getValue();
125
126
processSchema(schemaName, schema, openAPI);
127
}
128
}
129
130
private void processSchema(String name, Schema schema, OpenAPI openAPI) {
131
// Resolve any aliases or references
132
Schema resolvedSchema = ModelUtils.unaliasSchema(schema, openAPI);
133
134
if (ModelUtils.isObjectSchema(resolvedSchema)) {
135
processObjectSchema(name, resolvedSchema);
136
} else if (ModelUtils.isArraySchema(resolvedSchema)) {
137
processArraySchema(name, resolvedSchema);
138
} else if (ModelUtils.isStringSchema(resolvedSchema)) {
139
processStringSchema(name, resolvedSchema);
140
} else if (ModelUtils.isNumberSchema(resolvedSchema) || ModelUtils.isIntegerSchema(resolvedSchema)) {
141
processNumericSchema(name, resolvedSchema);
142
} else if (ModelUtils.isComposedSchema(resolvedSchema)) {
143
processComposedSchema(name, resolvedSchema);
144
}
145
}
146
147
private void processStringSchema(String name, Schema schema) {
148
if (ModelUtils.isDateSchema(schema)) {
149
System.out.println(name + " is a date field");
150
} else if (ModelUtils.isDateTimeSchema(schema)) {
151
System.out.println(name + " is a date-time field");
152
} else if (ModelUtils.isEmailSchema(schema)) {
153
System.out.println(name + " is an email field");
154
} else if (ModelUtils.isUUIDSchema(schema)) {
155
System.out.println(name + " is a UUID field");
156
} else if (ModelUtils.isBinarySchema(schema)) {
157
System.out.println(name + " is binary data");
158
}
159
}
160
}
161
```
162
163
### String Transformation
164
165
```java
166
public class NamingProcessor {
167
168
public void demonstrateStringTransformations() {
169
String input = "user_account_details";
170
171
// Convert to different naming conventions
172
String camelCase = StringUtils.camelize(input);
173
// Result: "userAccountDetails"
174
175
String pascalCase = StringUtils.camelize(input, CamelizeOption.UPPERCASE_FIRST_LETTER);
176
// Result: "UserAccountDetails"
177
178
String dashCase = StringUtils.dashize(camelCase);
179
// Result: "user-account-details"
180
181
String snakeCase = StringUtils.underscore(pascalCase);
182
// Result: "user_account_details"
183
184
System.out.println("Original: " + input);
185
System.out.println("camelCase: " + camelCase);
186
System.out.println("PascalCase: " + pascalCase);
187
System.out.println("dash-case: " + dashCase);
188
System.out.println("snake_case: " + snakeCase);
189
}
190
191
public String generateMethodName(String operationId) {
192
// Clean and transform operation ID to method name
193
String cleaned = operationId.replaceAll("[^a-zA-Z0-9_]", "_");
194
return StringUtils.camelize(cleaned, CamelizeOption.LOWERCASE_FIRST_LETTER);
195
}
196
197
public String generateClassName(String schemaName) {
198
// Transform schema name to class name
199
String cleaned = schemaName.replaceAll("[^a-zA-Z0-9_]", "_");
200
return StringUtils.camelize(cleaned, CamelizeOption.UPPERCASE_FIRST_LETTER);
201
}
202
203
public String sanitizeText(String input) {
204
// Create custom escaping rules
205
Map<String, String> escapeMapping = new HashMap<>();
206
escapeMapping.put("\"", "\\\"");
207
escapeMapping.put("\n", "\\n");
208
escapeMapping.put("\t", "\\t");
209
210
Set<String> allowedChars = Set.of("a-z", "A-Z", "0-9", " ", "_", "-");
211
Set<String> escapeChars = Set.of("\"", "\n", "\t", "\\");
212
213
return StringUtils.escape(input, escapeMapping, allowedChars, escapeChars);
214
}
215
}
216
```
217
218
### Version Comparison
219
220
```java
221
public class VersionManager {
222
223
public void compareVersions() {
224
SemVer current = new SemVer("2.1.0");
225
SemVer minimum = new SemVer("2.0.0");
226
SemVer target = new SemVer("2.2.0-beta");
227
SemVer latest = new SemVer("3.0.0");
228
229
// Basic comparisons
230
if (current.isGreaterThan(minimum)) {
231
System.out.println("Current version meets minimum requirement");
232
}
233
234
if (current.isLessThan(target)) {
235
System.out.println("Upgrade available to " + target.getVersion());
236
}
237
238
// Version component access
239
System.out.println("Current version components:");
240
System.out.println(" Major: " + current.getMajor());
241
System.out.println(" Minor: " + current.getMinor());
242
System.out.println(" Patch: " + current.getPatch());
243
244
if (target.getPrerelease() != null) {
245
System.out.println("Target is prerelease: " + target.getPrerelease());
246
}
247
248
// Sorting versions
249
List<SemVer> versions = Arrays.asList(latest, current, minimum, target);
250
Collections.sort(versions);
251
252
System.out.println("Versions in ascending order:");
253
for (SemVer version : versions) {
254
System.out.println(" " + version.toString());
255
}
256
}
257
258
public boolean isCompatibleVersion(String requiredVersion, String actualVersion) {
259
SemVer required = new SemVer(requiredVersion);
260
SemVer actual = new SemVer(actualVersion);
261
262
// Check if major versions match and actual is >= required
263
return actual.getMajor() == required.getMajor() &&
264
actual.isGreaterThan(required) || actual.isEquivalentTo(required);
265
}
266
267
public SemVer findLatestCompatibleVersion(List<String> availableVersions, String minimumVersion) {
268
SemVer minimum = new SemVer(minimumVersion);
269
270
return availableVersions.stream()
271
.map(SemVer::new)
272
.filter(version -> version.getMajor() == minimum.getMajor()) // Same major version
273
.filter(version -> version.isGreaterThan(minimum) || version.isEquivalentTo(minimum))
274
.max(SemVer::compareTo)
275
.orElse(null);
276
}
277
}
278
```
279
280
### Model Processing
281
282
```java
283
public class ModelProcessor {
284
285
public void processGeneratedModels(Map<String, ModelsMap> allModels) {
286
for (Map.Entry<String, ModelsMap> entry : allModels.entrySet()) {
287
String packageName = entry.getKey();
288
ModelsMap modelsMap = entry.getValue();
289
290
System.out.println("Processing package: " + packageName);
291
292
for (ModelMap modelMap : modelsMap.getModels()) {
293
CodegenModel model = (CodegenModel) modelMap.get("model");
294
processModel(model);
295
}
296
}
297
}
298
299
private void processModel(CodegenModel model) {
300
System.out.println("Processing model: " + model.classname);
301
302
// Find model by name in all models (utility method)
303
// CodegenModel foundModel = ModelUtils.getModelByName(model.name, allModels);
304
305
// Process model properties
306
for (CodegenProperty property : model.vars) {
307
processProperty(property, model);
308
}
309
310
// Handle inheritance
311
if (model.parent != null) {
312
System.out.println(" Extends: " + model.parent);
313
}
314
315
if (model.interfaces != null && !model.interfaces.isEmpty()) {
316
System.out.println(" Implements: " + String.join(", ", model.interfaces));
317
}
318
}
319
320
private void processProperty(CodegenProperty property, CodegenModel parentModel) {
321
// Apply naming conventions
322
String getterName = "get" + StringUtils.camelize(property.name, CamelizeOption.UPPERCASE_FIRST_LETTER);
323
String setterName = "set" + StringUtils.camelize(property.name, CamelizeOption.UPPERCASE_FIRST_LETTER);
324
325
property.getter = getterName;
326
property.setter = setterName;
327
328
// Add custom vendor extensions
329
property.vendorExtensions.put("x-custom-getter", getterName);
330
property.vendorExtensions.put("x-custom-setter", setterName);
331
property.vendorExtensions.put("x-parent-model", parentModel.classname);
332
333
System.out.println(" Property: " + property.name + " (" + property.dataType + ")");
334
}
335
}
336
```
337
338
### Reference Resolution
339
340
```java
341
public class ReferenceResolver {
342
343
public void resolveSchemaReferences(OpenAPI openAPI) {
344
Map<String, Schema> schemas = openAPI.getComponents().getSchemas();
345
346
for (Map.Entry<String, Schema> entry : schemas.entrySet()) {
347
String schemaName = entry.getKey();
348
Schema schema = entry.getValue();
349
350
resolveSchemaRefs(schemaName, schema, openAPI);
351
}
352
}
353
354
private void resolveSchemaRefs(String name, Schema schema, OpenAPI openAPI) {
355
if (schema.get$ref() != null) {
356
// Extract reference name
357
String refName = ModelUtils.getSimpleRef(schema.get$ref());
358
System.out.println("Schema " + name + " references: " + refName);
359
360
// Resolve the reference
361
Schema resolvedSchema = ModelUtils.unaliasSchema(schema, openAPI);
362
363
if (resolvedSchema != schema) {
364
System.out.println(" Resolved to actual schema");
365
processResolvedSchema(name, resolvedSchema, openAPI);
366
}
367
}
368
369
// Process properties that might contain references
370
if (schema.getProperties() != null) {
371
for (Map.Entry<String, Schema> propEntry : schema.getProperties().entrySet()) {
372
String propName = propEntry.getKey();
373
Schema propSchema = propEntry.getValue();
374
375
if (propSchema.get$ref() != null) {
376
String propRefName = ModelUtils.getSimpleRef(propSchema.get$ref());
377
System.out.println(" Property " + propName + " references: " + propRefName);
378
}
379
}
380
}
381
}
382
383
private void processResolvedSchema(String name, Schema schema, OpenAPI openAPI) {
384
// Process the resolved schema
385
if (ModelUtils.isObjectSchema(schema)) {
386
System.out.println(" Resolved to object schema");
387
} else if (ModelUtils.isArraySchema(schema)) {
388
System.out.println(" Resolved to array schema");
389
}
390
// ... other processing
391
}
392
}
393
```