-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.js
629 lines (554 loc) · 23.9 KB
/
main.js
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
const fsNew = require('fs-extra')
const nodeUtils = require('util');
const openAPI = require('./src/openapi');
const constant = require('./src/constant');
const jsonld = require('./src/jsonld/jsonld');
const vocabulary = require('./src/vocabulary');
const FileGenerator = require('./src/filegenerator');
var fs = require('fs');
var path = require('path');
const title = require('./package.json').title;
const description = require('./package.json').description;
const baseDirName = require('./package.json').name;
let vDialog = null;
var forEach = require('async-foreach').forEach;
var dElement = require('./src/diagram/dElement');
var utils = require('./src/utils');
var notAvailElement = require('./src/notavailelement');
const JSON_FILE_FILTERS = [{
name: 'JSON File',
extensions: ['json']
}]
/**
* @function generateSpecs
* @description Generates OpenAPI Specification When user select generate specs from Tools->OpenAPI-> Generate Specs
* @param {UMLPackage} umlPackage
* @param {Object} options
*/
function genSpecs(umlPackage, options = getGenOptions()) {
/* Clear old msgs from not availabe class and not linked type */
resetOldMsgs();
/* There are two modes of extension, TEST & GENERATE. Here we set APP_MODE_GEN. */
openAPI.setAppMode(openAPI.APP_MODE_GEN); /* 0 mode for Generate API */
/* If umlPackage is not assigned, popup ElementPicker */
if (!umlPackage) {
/* Open element picker dialog to pick package */
app.elementPickerDialog
.showDialog(constant.DIALOG_MSG_PICKERDIALOG, null, null) /* type.UMLPackage */
.then(function ({
buttonId,
returnValue
}) {
if (buttonId === "ok") {
let exportElement = returnValue;
openAPI.setExportElementName(exportElement.name);
let varSel = exportElement.getClassName();
let valPackagename = type.UMLPackage.name;
let valClassDiagram = type.UMLClassDiagram.name;
let eleTypeStr = '';
if (varSel == valClassDiagram) {
eleTypeStr = constant.STR_DIAGRAM
openAPI.setModelType(openAPI.APP_MODEL_DIAGRAM);
dElement.filterUMLClassDiagram(exportElement);
} else if (varSel == valPackagename) {
eleTypeStr = constant.STR_PACKAGE;
openAPI.setModelType(openAPI.APP_MODEL_PACKAGE);
} else {
app.dialogs.showErrorDialog(constant.DIALOG_MSG_ERROR_SELECT_PACKAGE);
return;
}
if (utils.isEmpty(exportElement)) {
let str = nodeUtils.format(constant.PACKAGE_SELECTION_ERROR, eleTypeStr, eleTypeStr);
app.dialogs.showErrorDialog(str);
return;
}
const options = getGenOptions();
fileTypeSelection(exportElement, options);
}
});
}
}
/**
* @function startOpenApiGenerator
* @description initialize package path directory, gets all element from package, generate openapi from package
* @param {string} message
* @param {UMLClassDiagram} exportElement
* @param {string} basePath
* @param {Object} options
* @param {integer} returnValue
*/
async function startOpenApiGenerator(message, exportElement, basePath, options, returnValue) {
const mOpenApi = new openAPI.OpenApi(exportElement, basePath, options, returnValue);
let dm = app.dialogs;
vDialog = dm.showModalDialog("", constant.titleopenapi, message, [], true);
/* Initialize coretypes */
utils.initCoreTypes();
setTimeout(async function () {
try {
/* Initialize package */
await mOpenApi.initUMLPackage();
/* Initialize model elements */
await mOpenApi.getModelElements();
/* Generate OpenAPI */
let resultGen = await mOpenApi.generateOpenAPI();
if (resultGen.result == constant.FIELD_SUCCESS) {
vDialog.close();
setTimeout(function () {
app.dialogs.showInfoDialog(resultGen.message);
}, 10);
vDialog = null;
}
} catch (err) {
vDialog.close();
setTimeout(function () {
app.dialogs.showErrorDialog(err.message);
console.error("Error getUMLModel", err);
}, 10);
}
}, 0);
}
/**
* @function fileTypeSelection
* @description Display dropdown dialog and allow user to select file type from dropdown dailog like (JSON & YAML, JSON, YAML)
* @param {UMLPackage} umljPackage
* @param {Object} options
*/
function fileTypeSelection(tempExportElement, options) {
app.dialogs.showSelectDropdownDialog(constant.msg_file_select, constant.fileOptions).then(function ({
buttonId,
returnValue
}) {
if (buttonId === 'ok') {
const basePath = app.dialogs.showSaveDialog(constant.msg_file_saveas, null, null);
if (basePath != null) {
setTimeout(function () {
let message = '';
if (openAPI.isModelPackage()) {
message = nodeUtils.format(constant.PROGRESS_MSG, tempExportElement.name, constant.STR_PACKAGE);
} else if (openAPI.isModelDiagram()) {
message = nodeUtils.format(constant.PROGRESS_MSG, tempExportElement.name, constant.STR_DIAGRAM);
}
startOpenApiGenerator(message, tempExportElement, basePath, options, returnValue);
}, 10);
} else {
console.log("Dialog cancelled : basePath not available")
}
} else {
console.log("Dialog cancelled")
}
});
}
/**
* @function selectPkgDiagram
* @description Display dropdown dialog and allow user to select 'Diagram or Package'
* @param {UMLPackage} umljPackage
* @param {Object} options
*/
function selectPkgDiagram() {
/* Clear old msgs from not availabe class and not linked type */
resetOldMsgs();
app.dialogs.showSelectDropdownDialog(constant.msg_pkg_diagram_select, constant.pkgOptions).then(function ({
buttonId,
returnValue
}) {
if (buttonId === 'ok') {
if (returnValue == 1 /* for Package */ ) {
testEntirePackage();
} else if (returnValue == 2 /* for Diagram */ ) {
testEntireDiagram();
}
} else {
console.log("Dialog cancelled")
}
});
}
/**
* @function getGenOptions
* @description returns the app preferences stored by user
* @returns {Object}
*/
function getGenOptions() {
return {
idlDoc: app.preferences.get(constant.PREF_GENDOC),
indentSpaces: [],
debug: app.preferences.get(constant.PREF_DEBUG_KEY)
};
}
function resetOldMsgs() {
/* Resetting for not available class or enum for Qualified attribute type */
notAvailElement.resetNotAvailableClassOrEnumeInFile();
/* Resetting for not linked type */
notAvailElement.resetNotLinkedType();
}
/**
* @function testSinglePackage
* @description Test single package which user has selected from elementPickerDialog
*/
function testSinglePackage() {
/* Clear old msgs from not availabe class and not linked type */
resetOldMsgs();
/* There are two modes of extension, TEST & GENERATE. Here we set TEST mode. */
openAPI.setAppMode(openAPI.APP_MODE_TEST);
/* There are two modes of TEST, TEST_MODE_SINGLE & TEST_MODE_ALL. Here we set TEST_MODE_SINGLE) */
openAPI.setTestMode(openAPI.TEST_MODE_SINGLE);
/* Open element picker dialog to pick package */
app.elementPickerDialog
.showDialog(constant.DIALOG_MSG_TEST_PICKERDIALOG, null, null)
.then(function ({
buttonId,
returnValue
}) {
if (buttonId === "ok") {
let exportElement = returnValue;
openAPI.setExportElementName(exportElement.name);
let varSel = exportElement.getClassName();
let valPackagename = type.UMLPackage.name;
let valClassDiagram = type.UMLClassDiagram.name;
let message = '';
let eleTypeStr = '';
if (varSel == valClassDiagram) {
eleTypeStr = constant.STR_DIAGRAM;
openAPI.setModelType(openAPI.APP_MODEL_DIAGRAM);
dElement.filterUMLClassDiagram(exportElement);
} else if (varSel == valPackagename) {
eleTypeStr = constant.STR_PACKAGE;
openAPI.setModelType(openAPI.APP_MODEL_PACKAGE);
} else {
app.dialogs.showErrorDialog(constant.DIALOG_MSG_ERROR_SELECT_PACKAGE);
return;
}
message = nodeUtils.format(constant.PROGRESS_MSG, exportElement.name, eleTypeStr);
if (utils.isEmpty(exportElement)) {
let str = nodeUtils.format(constant.PACKAGE_SELECTION_ERROR, eleTypeStr, eleTypeStr);
app.dialogs.showErrorDialog(str);
return;
}
const basePath = __dirname + constant.IDEAL_TEST_FILE_PATH;
const options = getGenOptions();
startOpenApiGenerator(message, exportElement, basePath, options, 1);
}
});
}
/**
* @function removeOutputFiles
* @description Remove previously test generated .json files from the output folder
*/
function removeOutputFiles() {
/* return new Promise((resolve, reject) => { */
const directory = __dirname + constant.IDEAL_TEST_FILE_PATH;
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
fs.readdir(directory, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
}
/**
* @function starTestingAllPackage
* @description Start testing all packages one by one of the project
* @params {UMLPackage} item
*/
async function starTestingAllDiagram(diagramList) {
let strModeType = ' for Diagram : ';
removeOutputFiles();
let strSummery = '';
for (const mUMLDiagram of diagramList) {
openAPI.setExportElementName(mUMLDiagram.name);
const basePath = __dirname + constant.IDEAL_TEST_FILE_PATH;
const options = getGenOptions();
openAPI.setModelType(openAPI.APP_MODEL_DIAGRAM);
dElement.filterUMLClassDiagram(mUMLDiagram);
const mOpenApi = new openAPI.OpenApi(mUMLDiagram, basePath, options, 1);
try {
/* Initialize package */
await mOpenApi.initUMLPackage()
/* Initialize model elements */
await mOpenApi.getModelElements();
/* Generate OpenAPI */
await mOpenApi.generateOpenAPI();
} catch (err) {
console.error("Error startTestingAllPackage", err);
if (openAPI.getError().hasOwnProperty('isDuplicate') && openAPI.getError().isDuplicate == true) {
let arrPath = openAPI.findHierarchy(mUMLDiagram);
let pkgPath = openAPI.reversePkgPath(arrPath);
let bindFailureMsg = constant.msgtesterror + strModeType + '\'' + openAPI.getExportElementName() + '\' {' + pkgPath + '}' + '\n' + constant.strerror + openAPI.getError().msg;
openAPI.addSummery(bindFailureMsg, 'failure');
}
}
}
vDialog.close();
vDialog = null;
setTimeout(function () {
console.log('Done!');
let summery = openAPI.getSummery();
let status = 'success';
summery.filter((item, index) => {
if (item.status == 'failure') {
status = 'failure'
}
strSummery += item.message + '\n\n';
});
if (status == 'success') {
app.dialogs.showInfoDialog(strSummery);
} else {
app.dialogs.showErrorDialog(strSummery);
}
}, 10);
}
/**
* @function starTestingAllPackage
* @description Start testing all packages one by one of the project
* @params {UMLPackage} item
*/
async function starTestingAllPackage(pkgList) {
let strModeType = ' for Package : ';
removeOutputFiles();
let strSummery = '';
for (const umlPackage of pkgList) {
openAPI.setExportElementName(umlPackage.name);
const basePath = __dirname + constant.IDEAL_TEST_FILE_PATH;
const options = getGenOptions();
const mOpenApi = new openAPI.OpenApi(umlPackage, basePath, options, 1);
try {
/* Initialize package */
await mOpenApi.initUMLPackage()
/* Initialize model elements */
await mOpenApi.getModelElements();
/* Generate OpenAPI */
await mOpenApi.generateOpenAPI();
} catch (err) {
/* app.dialogs.showErrorDialog(err.message); */
console.error("Error startTestingAllPackage", err);
if (openAPI.getError().hasOwnProperty('isDuplicate') && openAPI.getError().isDuplicate == true) {
let arrPath = openAPI.findHierarchy(umlPackage);
let pkgPath = openAPI.reversePkgPath(arrPath);
let bindFailureMsg = constant.msgtesterror + strModeType + '\'' + openAPI.getExportElementName() + '\' {' + pkgPath + '}' + '\n' + constant.strerror + openAPI.getError().msg;
openAPI.addSummery(bindFailureMsg, 'failure');
}
}
}
vDialog.close();
vDialog = null;
setTimeout(function () {
console.log('Done!');
let summery = openAPI.getSummery();
let status = 'success';
summery.filter((item, index) => {
if (item.status == 'failure') {
status = 'failure'
}
strSummery += item.message + '\n\n';
});
if (status == 'success') {
app.dialogs.showInfoDialog(strSummery);
} else {
app.dialogs.showErrorDialog(strSummery);
}
}, 10);
}
/**
* @function testEntirePackage
* @description Test Entire Project for all packages available in model for valid OpenApi Specifications
*/
function testEntirePackage() {
openAPI.setModelType(openAPI.APP_MODEL_PACKAGE);
var packages = app.repository.select("@UMLPackage")
/* reset old stored error summery */
openAPI.resetSummery();
/* There are two modes of extension, TEST & GENERATE. Here we set APP_MODE_TEST. */
openAPI.setAppMode(openAPI.APP_MODE_TEST);
/* There are two modes of TEST, TEST_MODE_SINGLE & TEST_MODE_ALL. Here we set TEST_MODE_ALL) */
openAPI.setTestMode(openAPI.TEST_MODE_ALL);
let mPackages = [];
packages.forEach(element => {
if (element instanceof type.UMLPackage) {
mPackages.push(element);
}
});
vDialog = null;
let dm = app.dialogs;
vDialog = dm.showModalDialog("", constant.titleopenapi, constant.PROGRESS_MSG_ENTIRE_PROJECT, [], true);
setTimeout(function () {
starTestingAllPackage(mPackages);
}, 10);
}
/**
* @function testEntireDiagram
* @description Test Entire Project for all diagrams available in model for valid OpenApi Specifications
*/
function testEntireDiagram() {
openAPI.setModelType(openAPI.APP_MODEL_DIAGRAM);
var umlClassDiagram = app.repository.select("@UMLClassDiagram")
/* reset old stored error summery */
openAPI.resetSummery();
/* There are two modes of extension, TEST & GENERATE. Here we set APP_MODE_TEST. */
openAPI.setAppMode(openAPI.APP_MODE_TEST);
/* There are two modes of TEST, TEST_MODE_SINGLE & TEST_MODE_ALL. Here we set TEST_MODE_ALL) */
openAPI.setTestMode(openAPI.TEST_MODE_ALL);
let mUMLDiagrams = [];
umlClassDiagram.forEach(element => {
if (element instanceof type.UMLClassDiagram) {
mUMLDiagrams.push(element);
}
});
vDialog = null;
let dm = app.dialogs;
vDialog = dm.showModalDialog("", constant.titleopenapi, constant.PROGRESS_MSG_ENTIRE_PROJECT, [], true);
setTimeout(function () {
starTestingAllDiagram(mUMLDiagrams);
}, 10);
}
/**
* @function aboutUsExtension
* @description Display Information about Extension like the title and description of OpenAPI Specification.
*/
function aboutUsExtension() {
app.dialogs.showInfoDialog(title + "\n\n" + description);
/* Script to change multiplicity from '1' to '0..1' */
/*
let allAttrib=app.repository.select("@UMLAttribute");
let attribMulticiplityOne=allAttrib.filter(function(attrib){
return attrib.multiplicity==="1";
});
forEach(attribMulticiplityOne,function(attrib){
app.engine.setProperty(attrib,"multiplicity","0..1");
}); */
}
/**
* @function aboutUsExtension
* @description Display Information about Extension like the title and description of OpenAPI Specification.
*/
function genJSONLD() {
/* Clear old msgs from not availabe class and not linked type */
resetOldMsgs();
openAPI.setAppMode(openAPI.APP_MODE_JSONLD)
/* Initialize coretypes */
utils.initCoreTypes();
/* Open element picker dialog to pick package */
app.elementPickerDialog
.showDialog(constant.JSONLD_MSG_PICKERDIALOG, null, null) /* type.UMLPackage */
.then(function ({
buttonId,
returnValue
}) {
if (buttonId === "ok") {
let varSel = returnValue.getClassName();
let valPackagename = type.UMLPackage.name;
if (varSel == valPackagename) {
if (!utils.isEmpty(returnValue)) {
var _filename = returnValue.name;
var basePath = app.dialogs.showSaveDialog('Export JSON-LD As JSON', _filename + '-vocabulary' + '.json', JSON_FILE_FILTERS);
if (basePath == null) {
console.log("Dialog cancelled : basePath not available")
return;
}
console.log("generateJSONLD");
jsonld.setExportElement(returnValue);
jsonld.setExportElementName(returnValue.name);
let dirPath = path.dirname(basePath);
jsonld.setFilePath(dirPath)
let objJSONLd = jsonld.generateJSONLD();
/* Will alert dialog for not availabel class or enume in file */
notAvailElement.showDialogInvalidAttributeType();
notAvailElement.showDialogNotLinkedType();
let generator = new FileGenerator();
generator.createJSONLD(basePath, objJSONLd).then(function (res) {
if (res.result == constant.FIELD_SUCCESS) {
app.dialogs.showInfoDialog(res.message);
}
}).catch(function (err) {
app.dialogs.showErrorDialog(err.message);
});;
console.log(objJSONLd);
} else {
app.dialogs.showErrorDialog(constant.PACKAGE_SELECTION_ERROR);
}
} else {
app.dialogs.showErrorDialog(constant.JSONLD_MSG_PICKERDIALOG);
}
}
});
}
/**
* @function initProject
* @description initialize basic json rules for jsonld and openapi/jsonschema
*/
function initProject() {
utils.initJsonRuleType();
utils.initJsonldRuleType();
}
/**
* @function init
* @description function will be called when the extension is loaded
*/
function init() {
/* Register command to Generate Specification */
app.commands.register('openapi:generate-specs', genSpecs);
/* Register command to Test Single Pacakge */
app.commands.register('openapi:test-single-package', testSinglePackage /* swaggerTest */ );
/* Register command to Test Entire Project */
app.commands.register('openapi:test-entire-package', selectPkgDiagram);
/* Register command to Display Extension information in dialog */
app.commands.register('openapi:about-us', aboutUsExtension);
/* Register command to Generate Generate JSON-LD Specification */
app.commands.register('jsonld:generate', genJSONLD);
app.commands.register('jsonld:import-vocabulary', vocabulary.importFromVocabulary);
app.commands.register('jsonld:import-vocabulary-url', vocabulary.importFromVocabularyURL);
app.commands.register('jsonld:import-context', vocabulary.importFromContext);
app.commands.register('jsonld:import-context-url', vocabulary.importFromContextURL);
app.commands.register('jsonld:import-uncefact-vocabulary', vocabulary.importUNCEFACT);
app.commands.register('jsonld:import-uncl', vocabulary.initUNCLEnumerations);
/* Register command to initialize project */
app.project.on('projectLoaded', initProject);
var openapiPreferences = {
id: "openapi",
name: "OpenAPI",
schema: {
"openapi.output": {
text: "OpenAPI output format",
description: "Pick one of the output formats to be used by default.",
type: "dropdown",
default: 3,
options: constant.fileOptions
},
"openapi.ndr": {
text: "Apply NDR rules",
description: "Apply NDR rules.",
type: "check",
default: true
}
}
}
app.preferences.register(openapiPreferences)
}
/**
* @function runStarUML
* @description This is script to run staruml project for Windows and Linux OS. This function will copy all project files in staruml installed directory
*/
function runStarUML() {
/* possible values of os 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', 'win32' */
let homeDirectory = os.homedir();
let dest = '';
let src = __dirname + path.sep;
if (os.platform == 'win32') {
dest = homeDirectory + path.sep + 'AppData' + path.sep + 'Roaming' + path.sep + 'StarUML' + path.sep + 'extensions' + path.sep + 'user' + path.sep + baseDirName + path.sep;
} else if (os.platform == 'linux') {
dest = homeDirectory + '.config' + path.sep + 'StarUML' + path.sep + 'extensions' + path.sep + 'user' + path.sep + baseDirName + path.sep;
}
console.log("platform : ", os.platform);
console.log("base : ", baseDirName);
console.log("src : ", src);
console.log("dest : ", dest);
console.log("Coping files..!")
fsNew.copy(src, dest)
.then(() => console.log('success!'))
.catch(err => console.error(err));
return '';
}
exports.init = init
exports.runStarUML = runStarUML