UNPKG

40.5 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6/* tslint:disable:variable-name */
7const Mustache_1 = __importDefault(require("./java/Mustache"));
8const System_1 = __importDefault(require("./java/System"));
9const OAuth2Definition_1 = __importDefault(require("./models/auth/OAuth2Definition"));
10const Json_1 = __importDefault(require("./java/Json"));
11const ObjectUtils_1 = __importDefault(require("./java/ObjectUtils"));
12const StringUtils_1 = __importDefault(require("./java/StringUtils"));
13const StringBuilder_1 = __importDefault(require("./java/StringBuilder"));
14const LoggerFactory_1 = __importDefault(require("./java/LoggerFactory"));
15const File_1 = __importDefault(require("./java/File"));
16const javaUtil_1 = require("./java/javaUtil");
17const IOUtils_1 = __importDefault(require("./java/IOUtils"));
18const AbstractGenerator_1 = __importDefault(require("./AbstractGenerator"));
19const CodegenConstants_1 = __importDefault(require("./CodegenConstants"));
20const InlineModelResolver_1 = __importDefault(require("./InlineModelResolver"));
21const GlobalSupportingFile_1 = __importDefault(require("./GlobalSupportingFile"));
22const CodegenIgnoreProcessor_1 = __importDefault(require("./ignore/CodegenIgnoreProcessor"));
23const TreeMap_1 = __importDefault(require("./java/TreeMap"));
24const path_1 = __importDefault(require("path"));
25const TemplateLocator_1 = require("./TemplateLocator");
26const InheritanceTreeSorter_1 = require("./InheritanceTreeSorter");
27const sortOperationId = (a, b) => a.operationId.localeCompare(b.operationId);
28const sortClassName = (a, b) => {
29 const a1 = (a && a.get('classname')) || '';
30 const b1 = b && b.get('classname');
31 return a1.localeCompare(b1);
32};
33const sortImports = (a, b) => a.get('import').localeCompare(b.get('import'));
34const sortModelName = (a, b) => {
35 const a1 = (a && a.get('model')) || '';
36 const b1 = b && b.get('model');
37 const aclassname = a1 && a1.classname;
38 const bclassname = b1 && b1.classname;
39 if (aclassname) {
40 return aclassname.localeCompare(bclassname);
41 }
42 if (!bclassname) {
43 return 0;
44 }
45 return -1;
46};
47const rethrow = (e, ...args) => {
48 Log.trace(e);
49 throw new Error(...args);
50};
51class DefaultGenerator extends AbstractGenerator_1.default {
52 static processMimeTypes(mimeTypeList, operation, source) {
53 if (mimeTypeList != null && mimeTypeList.length) {
54 const last = mimeTypeList.length - 1;
55 const c = mimeTypeList.map((key, i) => javaUtil_1.newHashMap(['mediaType', key], ['hasMore', i !== last]));
56 operation.put(source, c);
57 operation.put(`has${StringUtils_1.default.upperFirst(source)}`, true);
58 }
59 }
60 static generateParameterId(parameter) {
61 return parameter.getName() + ':' + parameter.getIn();
62 }
63 opts(opts) {
64 this.__opts = opts;
65 this.swagger = opts.getSwagger();
66 this.config = opts.getConfig();
67 this.ignoreProcessor = new CodegenIgnoreProcessor_1.default(this.config.getOutputDir());
68 this.config.additionalProperties().putAll(opts.getOpts().getProperties());
69 return this;
70 }
71 generate() {
72 let generateApis = null;
73 let generateModels = null;
74 let generateSupportingFiles = null;
75 let generateApiTests = null;
76 let generateApiDocumentation = null;
77 let generateModelTests = null;
78 let generateModelDocumentation = null;
79 let modelsToGenerate = null;
80 let apisToGenerate = null;
81 let supportingFilesToGenerate = null;
82 if (System_1.default.getProperty('models') != null) {
83 const modelNames = System_1.default.getProperty('models');
84 generateModels = true;
85 if (!(modelNames.length === 0)) {
86 modelsToGenerate = javaUtil_1.newHashSet(...modelNames.split(','));
87 }
88 }
89 if (System_1.default.getProperty('apis') != null) {
90 const apiNames = System_1.default.getProperty('apis');
91 generateApis = true;
92 if (!(apiNames.length === 0)) {
93 apisToGenerate = javaUtil_1.newHashSet(...apiNames.split(','));
94 }
95 }
96 if (System_1.default.getProperty('supportingFiles') != null) {
97 const supportingFiles = System_1.default.getProperty('supportingFiles');
98 generateSupportingFiles = true;
99 if (!(supportingFiles.length === 0)) {
100 supportingFilesToGenerate = javaUtil_1.newHashSet(...supportingFiles.split(','));
101 }
102 }
103 if (System_1.default.getProperty('modelTests') != null) {
104 generateModelTests = Boolean(System_1.default.getProperty('modelTests'));
105 }
106 if (System_1.default.getProperty('modelDocs') != null) {
107 generateModelDocumentation = Boolean(System_1.default.getProperty('modelDocs'));
108 }
109 if (System_1.default.getProperty('apiTests') != null) {
110 generateApiTests = Boolean(System_1.default.getProperty('apiTests'));
111 }
112 if (System_1.default.getProperty('apiDocs') != null) {
113 generateApiDocumentation = Boolean(System_1.default.getProperty('apiDocs'));
114 }
115 if (generateApis == null &&
116 generateModels == null &&
117 generateSupportingFiles == null) {
118 generateApis = true;
119 generateModels = true;
120 generateSupportingFiles = true;
121 }
122 else {
123 if (generateApis == null) {
124 generateApis = false;
125 }
126 if (generateModels == null) {
127 generateModels = false;
128 }
129 if (generateSupportingFiles == null) {
130 generateSupportingFiles = false;
131 }
132 }
133 if (generateModelTests == null) {
134 generateModelTests = true;
135 }
136 if (generateModelDocumentation == null) {
137 generateModelDocumentation = true;
138 }
139 if (generateApiTests == null) {
140 generateApiTests = true;
141 }
142 if (generateApiDocumentation == null) {
143 generateApiDocumentation = true;
144 }
145 this.config
146 .additionalProperties()
147 .put(CodegenConstants_1.default.GENERATE_API_TESTS, generateApiTests);
148 this.config
149 .additionalProperties()
150 .put(CodegenConstants_1.default.GENERATE_MODEL_TESTS, generateModelTests);
151 if (!generateApiTests && !generateModelTests) {
152 this.config
153 .additionalProperties()
154 .put(CodegenConstants_1.default.EXCLUDE_TESTS, true);
155 }
156 if (this.swagger == null || this.config == null) {
157 throw new Error('missing swagger input or config!');
158 }
159 if (System_1.default.getProperty('debugSwagger') != null) {
160 Json_1.default.prettyPrint(this.swagger);
161 }
162 const files = [];
163 this.config.processOpts();
164 this.config.preprocessSwagger(this.swagger);
165 this.config
166 .additionalProperties()
167 .put('generatedDate', new Date().toString());
168 this.config
169 .additionalProperties()
170 .put('generatorClass', this.config.constructor.name);
171 if (this.swagger.getInfo() != null) {
172 const info = this.swagger.getInfo();
173 if (info.getTitle() != null) {
174 this.config
175 .additionalProperties()
176 .put('appName', this.config.escapeText(info.getTitle()));
177 }
178 if (info.getVersion() != null) {
179 this.config
180 .additionalProperties()
181 .put('appVersion', this.config.escapeText(info.getVersion()));
182 }
183 if (StringUtils_1.default.isEmpty(info.getDescription())) {
184 this.config
185 .additionalProperties()
186 .put('appDescription', 'No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)');
187 }
188 else {
189 this.config
190 .additionalProperties()
191 .put('appDescription', this.config.escapeText(info.getDescription()));
192 }
193 if (info.getContact() != null) {
194 const contact = info.getContact();
195 this.config
196 .additionalProperties()
197 .put('infoUrl', this.config.escapeText(contact.getUrl()));
198 if (contact.getEmail() != null) {
199 this.config
200 .additionalProperties()
201 .put('infoEmail', this.config.escapeText(contact.getEmail()));
202 }
203 }
204 if (info.getLicense() != null) {
205 const license = info.getLicense();
206 if (license.getName() != null) {
207 this.config
208 .additionalProperties()
209 .put('licenseInfo', this.config.escapeText(license.getName()));
210 }
211 if (license.getUrl() != null) {
212 this.config
213 .additionalProperties()
214 .put('licenseUrl', this.config.escapeText(license.getUrl()));
215 }
216 }
217 if (info.getVersion() != null) {
218 this.config
219 .additionalProperties()
220 .put('version', this.config.escapeText(info.getVersion()));
221 }
222 if (info.getTermsOfService() != null) {
223 this.config
224 .additionalProperties()
225 .put('termsOfService', this.config.escapeText(info.getTermsOfService()));
226 }
227 }
228 if (this.swagger.getVendorExtensions() != null) {
229 this.config.vendorExtensions().putAll(this.swagger.getVendorExtensions());
230 }
231 const hostBuilder = StringBuilder_1.default();
232 let scheme;
233 if (this.swagger.getSchemes() != null &&
234 this.swagger.getSchemes().length > 0) {
235 scheme = this.config.escapeText(this.swagger.getSchemes()[0]);
236 }
237 else {
238 scheme = 'https';
239 }
240 scheme = this.config.escapeText(scheme);
241 hostBuilder.append(scheme);
242 hostBuilder.append('://');
243 if (this.swagger.getHost() != null) {
244 hostBuilder.append(this.swagger.getHost());
245 }
246 else {
247 hostBuilder.append('localhost');
248 }
249 if (this.swagger.getBasePath() != null) {
250 hostBuilder.append(this.swagger.getBasePath());
251 }
252 const contextPath = this.config.escapeText(this.swagger.getBasePath() == null ? '' : this.swagger.getBasePath());
253 const basePath = this.config.escapeText(hostBuilder.toString());
254 const basePathWithoutHost = this.config.escapeText(this.swagger.getBasePath());
255 const inlineModelResolver = new InlineModelResolver_1.default();
256 inlineModelResolver.flatten(this.swagger);
257 const allOperations = [];
258 const allModels = [];
259 const definitions = this.swagger.getDefinitions();
260 if (definitions != null) {
261 let modelKeys = definitions.keySet();
262 if (generateModels) {
263 if (javaUtil_1.isNotEmptySet(modelsToGenerate)) {
264 const updatedKeys = javaUtil_1.newHashSet();
265 for (const m of modelKeys) {
266 if (modelsToGenerate.contains(m)) {
267 updatedKeys.add(m);
268 }
269 }
270 modelKeys = updatedKeys;
271 }
272 let allProcessedModels = new TreeMap_1.default(new InheritanceTreeSorter_1.InheritanceTreeSorter(this, definitions));
273 for (const name of modelKeys) {
274 try {
275 if (this.config.importMapping().containsKey(name)) {
276 Log.info('Model ' + name + ' not imported due to import mapping');
277 continue;
278 }
279 const model = definitions.get(name);
280 const models = this.processModels(this.config, javaUtil_1.newHashMap([name, model]), definitions);
281 models.put('classname', this.config.toModelName(name));
282 models.putAll(this.config.additionalProperties());
283 allProcessedModels.set(name, models);
284 }
285 catch (e) {
286 rethrow(e, "Could not process model '" +
287 name +
288 "'.Please make sure that your schema is correct!", e);
289 }
290 }
291 allProcessedModels = this.config.postProcessAllModels(allProcessedModels);
292 for (const [name, models] of allProcessedModels) {
293 try {
294 if (this.config.importMapping().containsKey(name)) {
295 continue;
296 }
297 allModels.push(models.value.models[0]);
298 for (const [templateName, suffix,] of this.config.modelTemplateFiles()) {
299 const filename = this.config.modelFileFolder() +
300 File_1.default.separator +
301 this.config.toModelFilename(name) +
302 suffix;
303 if (!this.config.shouldOverwrite(filename)) {
304 Log.info('Skipped overwriting ' + filename);
305 continue;
306 }
307 const written = this.processTemplateToFile(models, templateName, filename);
308 if (written != null) {
309 files.push(written);
310 }
311 }
312 if (generateModelTests) {
313 for (const [templateName, suffix,] of this.config.modelTestTemplateFiles()) {
314 const filename = this.config.modelTestFileFolder() +
315 File_1.default.separator +
316 this.config.toModelTestFilename(name) +
317 suffix;
318 if (new File_1.default(filename).exists()) {
319 Log.info('File exists. Skipped overwriting ' + filename);
320 continue;
321 }
322 const written = this.processTemplateToFile(models, templateName, filename);
323 if (written != null) {
324 files.push(written);
325 }
326 }
327 }
328 if (generateModelDocumentation) {
329 for (const [templateName, suffix,] of this.config.modelDocTemplateFiles()) {
330 const filename = this.config.modelDocFileFolder() +
331 File_1.default.separator +
332 this.config.toModelDocFilename(name) +
333 suffix;
334 if (!this.config.shouldOverwrite(filename)) {
335 Log.info('Skipped overwriting ' + filename);
336 continue;
337 }
338 const written = this.processTemplateToFile(models, templateName, filename);
339 if (written != null) {
340 files.push(written);
341 }
342 }
343 }
344 }
345 catch (e) {
346 rethrow(e, "Could not generate model '" + name + "'", e);
347 }
348 }
349 }
350 }
351 if (System_1.default.getProperty('debugModels') != null) {
352 Log.info('############ Model info ############');
353 Json_1.default.prettyPrint(allModels);
354 }
355 let paths = this.processPaths(this.swagger.getPaths());
356 if (generateApis) {
357 if (javaUtil_1.isNotEmptySet(apisToGenerate)) {
358 const updatedPaths = new TreeMap_1.default();
359 for (const [m, p] of paths) {
360 if (apisToGenerate.contains(m)) {
361 updatedPaths.set(m, p);
362 }
363 }
364 paths = updatedPaths;
365 }
366 for (const [tag, ops] of paths) {
367 try {
368 ops.sort((one, another) => ObjectUtils_1.default.compare(one.operationId, another.operationId));
369 const operation = this.processOperations(this.config, tag, ops);
370 operation.put('basePath', basePath);
371 operation.put('basePathWithoutHost', basePathWithoutHost);
372 operation.put('contextPath', contextPath);
373 operation.put('baseName', tag);
374 operation.put('modelPackage', this.config.modelPackage());
375 operation.putAll(this.config.additionalProperties());
376 operation.put('classname', this.config.toApiName(tag));
377 operation.put('classVarName', this.config.toApiVarName(tag));
378 operation.put('importPath', this.config.toApiImport(tag));
379 if (javaUtil_1.isNotEmptySet(this.config.vendorExtensions())) {
380 operation.put('vendorExtensions', this.config.vendorExtensions());
381 }
382 let sortParamsByRequiredFlag = true;
383 if (this.config
384 .additionalProperties()
385 .containsKey(CodegenConstants_1.default.SORT_PARAMS_BY_REQUIRED_FLAG)) {
386 sortParamsByRequiredFlag = Boolean(this.config
387 .additionalProperties()
388 .get(CodegenConstants_1.default.SORT_PARAMS_BY_REQUIRED_FLAG));
389 }
390 operation.put('sortParamsByRequiredFlag', sortParamsByRequiredFlag);
391 DefaultGenerator.processMimeTypes(this.swagger.getConsumes(), operation, 'consumes');
392 DefaultGenerator.processMimeTypes(this.swagger.getProduces(), operation, 'produces');
393 allOperations.push(operation);
394 for (let i = 0; i < allOperations.length; i++) {
395 const oo = allOperations[i];
396 if (i < allOperations.length - 1) {
397 oo.put('hasMore', 'true');
398 }
399 }
400 for (const [templateName] of this.config.apiTemplateFiles()) {
401 const filename = this.config.apiFilename(templateName, tag);
402 if (!this.config.shouldOverwrite(filename) &&
403 new File_1.default(filename).exists()) {
404 Log.info('Skipped overwriting ' + filename);
405 continue;
406 }
407 if (this.config.shouldGenerateApiFor(templateName, operation)) {
408 const written = this.processTemplateToFile(operation, templateName, filename);
409 if (written != null) {
410 files.push(written);
411 }
412 }
413 }
414 const requestDataObjects = operation.get('requestDataObjects');
415 if (requestDataObjects) {
416 for (const requestDataObject of requestDataObjects) {
417 for (const [templateName] of this.config.apiDataTemplateFile()) {
418 const filename = this.config.apiDataFilename(templateName, requestDataObject.requestDataType);
419 if (!this.config.shouldOverwrite(filename) &&
420 new File_1.default(filename).exists()) {
421 Log.info('Skipped overwriting ' + filename);
422 continue;
423 }
424 const written = this.processTemplateToFile(requestDataObject, templateName, filename);
425 if (written != null) {
426 files.push(written);
427 }
428 }
429 }
430 }
431 if (generateApiTests) {
432 for (const [templateName] of this.config.apiTestTemplateFiles()) {
433 const filename = this.config.apiTestFilename(templateName, tag);
434 if (new File_1.default(filename).exists()) {
435 Log.info('File exists. Skipped overwriting ' + filename);
436 continue;
437 }
438 const written = this.processTemplateToFile(operation, templateName, filename);
439 if (written != null) {
440 files.push(written);
441 }
442 }
443 }
444 if (generateApiDocumentation) {
445 for (const [templateName] of this.config.apiDocTemplateFiles()) {
446 const filename = path_1.default.normalize(this.config.apiDocFilename(templateName, tag));
447 if (!this.config.shouldOverwrite(filename) &&
448 new File_1.default(filename).exists()) {
449 Log.info('Skipped overwriting ' + filename);
450 continue;
451 }
452 const written = this.processTemplateToFile(operation, templateName, filename);
453 if (written != null) {
454 files.push(written);
455 }
456 }
457 }
458 }
459 catch (e) {
460 rethrow(e, "Could not generate api file for '" + tag + "'", e);
461 }
462 }
463 }
464 if (System_1.default.getProperty('debugOperations') != null) {
465 Log.info('############ Operation info ############');
466 Json_1.default.prettyPrint(allOperations);
467 }
468 const bundle = javaUtil_1.newHashMap();
469 bundle.putAll(this.config.additionalProperties());
470 bundle.put('apiPackage', this.config.apiPackage());
471 if (this.swagger.getHost() != null) {
472 bundle.put('host', this.swagger.getHost());
473 }
474 bundle.put('swagger', this.swagger);
475 bundle.put('basePath', basePath);
476 bundle.put('basePathWithoutHost', basePathWithoutHost);
477 bundle.put('scheme', scheme);
478 bundle.put('contextPath', contextPath);
479 // Sort to make stable.
480 bundle.put('apiInfo', {
481 apis: javaUtil_1.Collections.sort(allOperations, sortClassName),
482 });
483 bundle.put('models', javaUtil_1.Collections.sort(allModels, sortModelName));
484 bundle.put('apiFolder',
485 /* replace */ this.config
486 .apiPackage()
487 .split('.')
488 .join(File_1.default.separatorChar));
489 bundle.put('modelPackage', this.config.modelPackage());
490 const authMethods = this.config.fromSecurity(this.swagger.getSecurityDefinitions());
491 if (javaUtil_1.isNotEmptySet(authMethods)) {
492 bundle.put('authMethods', authMethods);
493 bundle.put('hasAuthMethods', true);
494 let authMethod;
495 for (authMethod of authMethods) {
496 authMethod.hasMore = true;
497 }
498 authMethod.hasMore = false;
499 }
500 if (this.swagger.getExternalDocs() != null) {
501 bundle.put('externalDocs', this.swagger.getExternalDocs());
502 }
503 for (let i = 0; i < allModels.length - 1; i++) {
504 const cm = allModels[i];
505 const m = cm.get('model');
506 m.hasMoreModels = true;
507 }
508 this.config.postProcessSupportingFileData(bundle);
509 if (System_1.default.getProperty('debugSupportingFiles') != null) {
510 Log.info('############ Supporting file info ############');
511 Json_1.default.prettyPrint(bundle);
512 }
513 if (generateSupportingFiles) {
514 for (const support of this.config.supportingFiles()) {
515 try {
516 let outputFolder = this.config.outputFolder();
517 if (StringUtils_1.default.isNotEmpty(support.folder)) {
518 outputFolder += File_1.default.separator + support.folder;
519 }
520 const of = new File_1.default(outputFolder);
521 if (!of.isDirectory()) {
522 of.mkdirs();
523 }
524 const outputFilename = outputFolder + File_1.default.separator + (support.destinationFilename || '');
525 if (!this.config.shouldOverwrite(outputFilename)) {
526 Log.info('Skipped overwriting ' + outputFilename);
527 continue;
528 }
529 let templateFile;
530 if (support != null && support instanceof GlobalSupportingFile_1.default) {
531 templateFile = this._resolveFile(this.config.getCommonTemplateDir(), support.templateFile || '');
532 }
533 else {
534 templateFile = this.getFullTemplateFile(this.config, support.templateFile);
535 }
536 if (templateFile == null) {
537 Log.warn(`Could not resolve ${support.templateFile}`);
538 continue;
539 }
540 let shouldGenerate = true;
541 if (javaUtil_1.isNotEmptySet(supportingFilesToGenerate)) {
542 if (supportingFilesToGenerate.contains(support.destinationFilename)) {
543 shouldGenerate = true;
544 }
545 else {
546 shouldGenerate = false;
547 }
548 }
549 if (shouldGenerate) {
550 if (this.ignoreProcessor.allowsFile(new File_1.default(outputFilename))) {
551 if (templateFile == null) {
552 Log.warn(`Could not resolve template file ${support.templateFile}`);
553 }
554 else if (templateFile.endsWith('.mustache')) {
555 const template = this.readTemplate(templateFile);
556 const tmpl = Mustache_1.default.compiler()
557 .withLoader(new TemplateLocator_1.TemplateLocator(this))
558 .defaultValue('')
559 .compile(template, templateFile);
560 this.writeToFile(outputFilename, tmpl.execute(bundle));
561 files.push(new File_1.default(outputFilename));
562 }
563 else {
564 const input = new File_1.default(templateFile);
565 const outputFile = new File_1.default(outputFilename);
566 const out = new File_1.default(outputFile);
567 Log.info('writing file ' + outputFile);
568 IOUtils_1.default.copy(input, out);
569 files.push(outputFile);
570 }
571 }
572 else {
573 Log.info('Skipped generation of ' +
574 outputFilename +
575 ' due to rule in .swagger-codegen-ignore');
576 }
577 }
578 }
579 catch (e) {
580 rethrow(e, "Could not generate supporting file '" + support + "'", e);
581 }
582 }
583 if (this.config.addSwaggerIgnoreFile()) {
584 const swaggerCodegenIgnore = '.swagger-codegen-ignore';
585 const ignoreFileNameTarget = this.config.outputFolder() + File_1.default.separator + swaggerCodegenIgnore;
586 const ignoreFile = new File_1.default(ignoreFileNameTarget);
587 if (!ignoreFile.exists()) {
588 const ignoreFileNameSource = this._resolveFilePath(this.config.getCommonTemplateDir(), swaggerCodegenIgnore);
589 const ignoreFileContents = this.readResourceContents(ignoreFileNameSource);
590 try {
591 this.writeToFile(ignoreFileNameTarget, ignoreFileContents);
592 }
593 catch (e) {
594 rethrow(e, "Could not generate supporting file '" +
595 swaggerCodegenIgnore +
596 "'", e);
597 }
598 files.push(ignoreFile);
599 }
600 }
601 if (this.config.addLicenseFile()) {
602 const apache2License = 'LICENSE';
603 const licenseFileNameTarget = this.config.outputFolder() + File_1.default.separator + apache2License;
604 const licenseFile = new File_1.default(licenseFileNameTarget);
605 const licenseFileNameSource = File_1.default.separator +
606 this.config.getCommonTemplateDir() +
607 File_1.default.separator +
608 apache2License;
609 const licenseFileContents = this.readResourceContents(licenseFileNameSource);
610 try {
611 this.writeToFile(licenseFileNameTarget, licenseFileContents);
612 }
613 catch (e) {
614 rethrow(e, "Could not generate LICENSE file '" + apache2License + "'", e);
615 }
616 files.push(licenseFile);
617 }
618 }
619 this.config.processSwagger(this.swagger);
620 return files;
621 }
622 processTemplateToFile(templateData, templateName, outputFilename) {
623 if (this.ignoreProcessor.allowsFile(new File_1.default(outputFilename))) {
624 const templateFile = this.getFullTemplateFile(this.config, templateName);
625 const template = this.readTemplate(templateFile);
626 const tmpl = Mustache_1.default.compiler()
627 .withLoader(new TemplateLocator_1.TemplateLocator(this))
628 .defaultValue('')
629 .compile(template, templateFile);
630 this.writeToFile(outputFilename, tmpl.execute(templateData));
631 return new File_1.default(outputFilename);
632 }
633 Log.info('Skipped generation of ' +
634 outputFilename +
635 ' due to rule in .swagger-codegen-ignore');
636 return null;
637 }
638 processPaths(paths) {
639 const ops = javaUtil_1.newHashMap();
640 for (const p of paths) {
641 const resourcePath = p.path;
642 this.processOperation(resourcePath, 'get', p.getGet(), ops);
643 this.processOperation(resourcePath, 'head', p.getHead(), ops);
644 this.processOperation(resourcePath, 'put', p.getPut(), ops);
645 this.processOperation(resourcePath, 'post', p.getPost(), ops);
646 this.processOperation(resourcePath, 'delete', p.getDelete(), ops);
647 this.processOperation(resourcePath, 'patch', p.getPatch(), ops);
648 this.processOperation(resourcePath, 'options', p.getOptions(), ops);
649 this.processOperation(resourcePath, 'event', p.getEvent(), ops);
650 }
651 return ops;
652 }
653 fromSecurity(name) {
654 const map = this.swagger.getSecurityDefinitions();
655 if (map == null) {
656 return null;
657 }
658 return map.get(name);
659 }
660 processOperation(resourcePath, httpMethod, operation, operations) {
661 if (operation == null) {
662 return;
663 }
664 if (System_1.default.getProperty('debugOperations') != null) {
665 Log.info('processOperation: resourcePath= ' +
666 resourcePath +
667 '\t;' +
668 httpMethod +
669 ' ' +
670 operation +
671 '\n');
672 }
673 let tags = operation.getTags();
674 if (tags == null) {
675 tags = [];
676 tags.push('default');
677 }
678 const operationParameters = javaUtil_1.newHashSet();
679 if (operation.getParameters() != null) {
680 for (const parameter of operation.getParameters()) {
681 operationParameters.add(DefaultGenerator.generateParameterId(parameter));
682 }
683 for (const parameter of operation.getParameters()) {
684 if (!operationParameters.contains(DefaultGenerator.generateParameterId(parameter))) {
685 operation.addParameter(parameter);
686 }
687 }
688 }
689 for (const tag of tags) {
690 let co = null;
691 try {
692 co = this.config.fromOperation(resourcePath, httpMethod, operation, this.swagger.getDefinitions(), this.swagger);
693 co.tags = [this.config.sanitizeTag(tag)];
694 this.config.addOperationToGroup(this.config.sanitizeTag(tag), resourcePath, operation, co, operations);
695 let securities = operation.getSecurity();
696 if (securities == null && this.swagger.getSecurity() != null) {
697 securities = [];
698 for (const sr of this.swagger.getSecurity()) {
699 securities.push(sr.getRequirements());
700 }
701 }
702 if (!javaUtil_1.isNotEmptySet(securities)) {
703 continue;
704 }
705 const authMethods = javaUtil_1.newHashMap();
706 for (const security of securities) {
707 for (const securityName of Object.keys(security)) {
708 const securityDefinition = this.fromSecurity(securityName);
709 if (securityDefinition != null) {
710 if (securityDefinition != null &&
711 securityDefinition instanceof OAuth2Definition_1.default) {
712 const oauth2Definition = securityDefinition;
713 const oauth2Operation = new OAuth2Definition_1.default();
714 oauth2Operation.setType(oauth2Definition.getType());
715 oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl());
716 oauth2Operation.setFlow(oauth2Definition.getFlow());
717 oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
718 oauth2Operation.setScopes(javaUtil_1.newHashMap());
719 for (const scope of security[securityName]) {
720 if (scope in oauth2Definition.getScopes()) {
721 oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
722 }
723 }
724 authMethods.put(securityName, securityDefinition);
725 }
726 else {
727 authMethods.put(securityName, securityDefinition);
728 }
729 }
730 }
731 }
732 if (javaUtil_1.isNotEmptySet(authMethods)) {
733 co.authMethods = this.config.fromSecurity(authMethods);
734 co.hasAuthMethods = true;
735 }
736 }
737 catch (ex) {
738 const msg = 'Could not process operation:\n Tag: ' +
739 tag +
740 '\n Operation: ' +
741 operation.getOperationId() +
742 '\n Resource: ' +
743 httpMethod +
744 ' ' +
745 resourcePath +
746 '\n Definitions: ' +
747 this.swagger.getDefinitions() +
748 '\n Exception: ' +
749 ex.message;
750 rethrow(ex, msg, ex);
751 }
752 }
753 }
754 processOperations(config, tag, ops) {
755 let counter = 0;
756 javaUtil_1.Collections.sort(ops, sortOperationId);
757 const opIds = javaUtil_1.newHashSet();
758 for (const op of ops) {
759 const opId = op.nickname;
760 if (opIds.contains(opId)) {
761 counter++;
762 op.nickname += '_' + counter;
763 }
764 opIds.add(opId);
765 }
766 const allImports = javaUtil_1.newHashSet();
767 for (const op of ops) {
768 allImports.addAll(op.imports);
769 }
770 const imports = [];
771 for (const nextImport of allImports) {
772 let mapping = config.importMapping().get(nextImport);
773 if (mapping == null) {
774 mapping = config.toModelImport(nextImport);
775 }
776 if (mapping != null) {
777 imports.push(javaUtil_1.newHashMap(['import', mapping]));
778 }
779 }
780 javaUtil_1.Collections.sort(imports, sortImports);
781 const operations = javaUtil_1.newHashMap(['imports', imports], ['hasImport', imports.length > 0], [
782 'operations',
783 javaUtil_1.newHashMap(['classname', config.toApiName(tag)], ['pathPrefix', config.toApiVarName(tag)], ['operation', ops]),
784 ], ['package', config.apiPackage()]);
785 config.postProcessOperations(operations);
786 // perhaps more where added?
787 let lastOp;
788 for ( /* const [TSCONV] */lastOp of operations
789 .get('operations')
790 .get('operation')) {
791 lastOp.hasMore = true;
792 }
793 if (lastOp) {
794 lastOp.hasMore = false;
795 }
796 return operations;
797 }
798 processModels(config, definitions, allDefinitions) {
799 const models = [];
800 const imports = [];
801 const objs = javaUtil_1.newHashMap(['package', config.modelPackage()], ['models', models], ['imports', imports]);
802 const allImports = javaUtil_1.newHashSet();
803 const importSet = javaUtil_1.newHashSet();
804 for (const [key, mm] of definitions) {
805 const cm = config.fromModel(key, mm, allDefinitions);
806 models.push(javaUtil_1.newHashMap(['model', cm], ['importPath', config.toModelImport(cm.classname)]));
807 allImports.addAll(cm.imports);
808 }
809 for (const nextImport of allImports) {
810 let mapping = config.importMapping().get(nextImport);
811 if (mapping == null) {
812 mapping = config.toModelImport(nextImport);
813 }
814 if (mapping != null && !config.defaultIncludes().contains(mapping)) {
815 importSet.add(mapping);
816 }
817 mapping = config.instantiationTypes().get(nextImport);
818 if (mapping != null && !config.defaultIncludes().contains(mapping)) {
819 importSet.add(mapping);
820 }
821 }
822 for (const s of importSet) {
823 imports.push(javaUtil_1.newHashMap(['import', s]));
824 }
825 config.postProcessModels(objs);
826 return objs;
827 }
828}
829exports.default = DefaultGenerator;
830const Log = LoggerFactory_1.default.getLogger(DefaultGenerator);
831//# sourceMappingURL=DefaultGenerator.js.map
\No newline at end of file