-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava.ts
1184 lines (1016 loc) · 46.7 KB
/
java.ts
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import clone = require('clone');
import fs = require('fs-extra');
import spec = require('jsii-spec');
import path = require('path');
import xmlbuilder = require('xmlbuilder');
import { Generator } from '../generator';
import logging = require('../logging');
import { PackageInfo, Target, TargetOptions } from '../target';
import { shell } from '../util';
import { VERSION, VERSION_DESC } from '../version';
// tslint:disable-next-line:no-var-requires
const spdxLicenseList = require('spdx-license-list');
export default class Java extends Target {
public static toPackageInfos(assm: spec.Assembly): { [language: string]: PackageInfo } {
const groupId = assm.targets!.java!.maven.groupId;
const artifactId = assm.targets!.java!.maven.artifactId;
const url = `https://repo1.maven.org/maven2/${groupId.replace(/\./g, '/')}/${artifactId}/${assm.version}/`;
return {
java: {
repository: 'Maven Central', url,
usage: {
'Apache Maven': {
language: 'xml',
code: xmlbuilder.create({
dependency: { groupId, artifactId, version: assm.version }
}).end({ pretty: true }).replace(/<\?\s*xml(\s[^>]+)?>\s*/m, '')
},
'Apache Buildr': `'${groupId}:${artifactId}:jar:${assm.version}'`,
'Apache Ivy': {
language: 'xml',
code: xmlbuilder.create({
dependency: { '@groupId': groupId, '@name': artifactId, '@rev': assm.version }
}).end({ pretty: true }).replace(/<\?\s*xml(\s[^>]+)?>\s*/m, '')
},
'Groovy Grape': `@Grapes(\n@Grab(group='${groupId}', module='${artifactId}', version='${assm.version}')\n)`,
'Gradle / Grails': `compile '${groupId}:${artifactId}:${assm.version}'`,
}
}
};
}
public static toNativeReference(type: spec.Type, options: any) {
const [, ...name] = type.fqn.split('.');
return { java: `import ${[options.package, ...name].join('.')};` };
}
protected readonly generator = new JavaGenerator();
constructor(options: TargetOptions) {
super(options);
}
public async build(sourceDir: string, outDir: string): Promise<void> {
const url = `file://${outDir}`;
const mvnArguments = new Array<string>();
for (const arg of Object.keys(this.arguments)) {
if (!arg.startsWith('mvn-')) { continue; }
mvnArguments.push(`--${arg.slice(4)}`);
mvnArguments.push(this.arguments[arg].toString());
}
const userXml = await this.generateMavenSettingsForLocalDeps(sourceDir, outDir);
await shell(
'mvn',
[...mvnArguments, 'deploy', `-D=altDeploymentRepository=local::default::${url}`, `--settings=${userXml}`],
{ cwd: sourceDir }
);
}
/**
* Generates maven settings file for this build.
* @param sourceDir The generated sources directory. This is where user.xml will be placed.
* @param currentOutputDirectory The current output directory. Will be added as a local maven repo.
*/
private async generateMavenSettingsForLocalDeps(sourceDir: string, currentOutputDirectory: string) {
const filePath = path.join(sourceDir, 'user.xml');
// traverse the dep graph of this module and find all modules that have
// an <outdir>/java directory. we will add those as local maven
// repositories which will resolve instead of Maven Central for those
// module. this enables building against local modules (i.e. in lerna
// repositories or linked modules).
const localRepos = await this.findLocalDepsOutput(this.packageDir);
// add the current output directory as a local repo as well for the case
// where we build multiple packages into the same output.
localRepos.push(currentOutputDirectory);
// if java-runtime is checked-out and we can find a local repository,
// add it to the list.
const localJavaRuntime = await findJavaRuntimeLocalRepository();
if (localJavaRuntime) {
localRepos.push(localJavaRuntime);
}
logging.debug('local maven repos:', localRepos);
const profileName = 'local-jsii-modules';
const settings = xmlbuilder.create({
settings: {
'@xmlns': 'http://maven.apache.org/POM/4.0.0',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'@xsi:schemaLocation': 'http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd',
'#comment': [
`Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`,
],
'profiles': {
profile: {
id: profileName,
repositories: {
repository: localRepos.map((repo, index) => ({
id: `local${index}`,
url: `file://${repo}`
}))
}
}
},
'activeProfiles': {
activeProfile: profileName
}
}
}, { encoding: 'UTF-8' }).end({ pretty: true });
logging.debug(`Generated ${filePath}`);
await fs.writeFile(filePath, settings);
return filePath;
}
}
// ##################
// # CODE GENERATOR #
// ##################
const MODULE_CLASS_NAME = '$Module';
const INTERFACE_PROXY_CLASS_NAME = 'Jsii$Proxy';
const JSR305_NULLABLE = '@javax.annotation.Nullable';
class JavaGenerator extends Generator {
/** If false, @Generated will not include generator version nor timestamp */
private emitFullGeneratorInfo?: boolean;
private moduleClass: string;
/**
* A map of all the modules ever referenced during code generation. These include
* direct dependencies but can potentially also include transitive dependencies, when,
* for example, we need to refer to their types when flatting the class hierarchy for
* interface proxies.
*/
private readonly referencedModules: { [name: string]: spec.PackageVersion } = { };
constructor() {
super({ generateOverloadsForMethodWithOptionals: true });
}
protected onBeginAssembly(assm: spec.Assembly, fingerprint: boolean) {
this.emitFullGeneratorInfo = fingerprint;
this.moduleClass = this.emitModuleFile(assm);
}
protected onEndAssembly(assm: spec.Assembly, fingerprint: boolean) {
this.emitMavenPom(assm, fingerprint);
delete this.emitFullGeneratorInfo;
}
protected getAssemblyOutputDir(mod: spec.Assembly) {
const dir = this.toNativeFqn(mod.name).replace(/\./g, '/');
return path.join('src', 'main', 'resources', dir);
}
protected onBeginClass(cls: spec.ClassType, abstract: boolean) {
this.openFileIfNeeded(cls);
this.addJavaDocs(cls);
const classBase = this.getClassBase(cls);
const extendsExpression = classBase ? ` extends ${classBase}` : '';
let implementsExpr = '';
if (cls.interfaces && cls.interfaces.length > 0) {
implementsExpr = ' implements ' + cls.interfaces.map(x => this.toNativeFqn(x.fqn!));
}
const nested = this.isNested(cls);
const inner = nested ? ' static' : '';
const absPrefix = abstract ? ' abstract' : '';
if (!nested) { this.emitGeneratedAnnotation(); }
this.code.line(`@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${cls.fqn}")`);
this.code.openBlock(`public${inner}${absPrefix} class ${cls.name}${extendsExpression}${implementsExpr}`);
this.emitJsiiInitializers(cls.name);
this.emitStaticInitializer(cls);
}
protected onEndClass(cls: spec.ClassType) {
if (cls.abstract) {
this.emitInterfaceProxy(cls);
}
this.code.closeBlock();
this.closeFileIfNeeded(cls);
}
protected onInitializer(cls: spec.ClassType, method: spec.Method) {
this.addJavaDocs(method);
this.code.openBlock(`${this.renderAccessLevel(method)} ${cls.name}(${this.renderMethodParameters(method)})`);
this.code.line('super(software.amazon.jsii.JsiiObject.InitializationMode.Jsii);');
this.code.line(`software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this${this.renderMethodCallArguments(method)});`);
this.code.closeBlock();
}
protected onInitializerOverload(cls: spec.ClassType, overload: spec.Method, originalInitializer: spec.Method) {
this.onInitializer(cls, overload);
/* tslint:disable-next-line no-unused-expression */
originalInitializer;
}
protected onField(cls: spec.ClassType, prop: spec.Property, union?: spec.UnionTypeReference) {
/* tslint:disable-next-line no-unused-expression */
cls; prop; union;
}
protected onProperty(cls: spec.ClassType, prop: spec.Property) {
this.emitProperty(cls, prop);
}
protected onStaticProperty(cls: spec.ClassType, prop: spec.Property) {
if (prop.const) {
this.emitConstProperty(prop);
} else {
this.emitProperty(cls, prop);
}
}
/**
* Since we expand the union setters, we will use this event to only emit the getter which returns an Object.
*/
protected onUnionProperty(cls: spec.ClassType, prop: spec.Property, _union: spec.UnionTypeReference) {
this.emitProperty(cls, prop);
}
protected onMethod(cls: spec.ClassType, method: spec.Method) {
this.emitMethod(cls, method);
}
protected onMethodOverload(cls: spec.ClassType, overload: spec.Method, _originalMethod: spec.Method) {
this.onMethod(cls, overload);
}
protected onStaticMethod(cls: spec.ClassType, method: spec.Method) {
this.emitMethod(cls, method);
}
protected onStaticMethodOverload(cls: spec.ClassType, overload: spec.Method, _originalMethod: spec.Method) {
this.emitMethod(cls, overload);
}
protected onBeginEnum(enm: spec.EnumType) {
this.openFileIfNeeded(enm);
this.addJavaDocs(enm);
if (!this.isNested(enm)) { this.emitGeneratedAnnotation(); }
this.code.line(`@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${enm.fqn}")`);
this.code.openBlock(`public enum ${enm.name}`);
}
protected onEndEnum(enm: spec.EnumType) {
this.code.closeBlock();
this.closeFileIfNeeded(enm);
}
protected onEnumMember(_: spec.EnumType, member: spec.EnumMember) {
this.addJavaDocs(member);
this.code.line(`${member.name},`);
}
// namespaces are handled implicitly by onBeginClass().
protected onBeginNamespace(ns: string) {
/* tslint:disable-next-line no-unused-expression */
ns;
}
protected onEndNamespace(ns: string) {
/* tslint:disable-next-line no-unused-expression */
ns;
}
protected onBeginInterface(ifc: spec.InterfaceType) {
this.openFileIfNeeded(ifc);
this.addJavaDocs(ifc);
// all interfaces always extend JsiiInterface so we can identify that it is a jsii interface.
const interfaces = ifc.interfaces || [];
const bases = [ 'software.amazon.jsii.JsiiSerializable', ...interfaces.map(x => this.toNativeFqn(x.fqn!)) ].join(', ');
const nested = this.isNested(ifc);
const inner = nested ? ' static' : '';
if (!nested) { this.emitGeneratedAnnotation(); }
this.code.openBlock(`public${inner} interface ${ifc.name} extends ${bases}`);
}
protected onEndInterface(ifc: spec.InterfaceType) {
if (ifc.datatype) {
this.emitInterfaceBuilder(ifc);
}
// emit interface proxy class
this.emitInterfaceProxy(ifc);
this.code.closeBlock();
this.closeFileIfNeeded(ifc);
}
protected onInterfaceMethod(_ifc: spec.InterfaceType, method: spec.Method) {
const returnType = method.returns ? this.toJavaType(method.returns) : 'void';
this.addJavaDocs(method);
this.code.line(`${returnType} ${method.name}(${this.renderMethodParameters(method)});`);
}
protected onInterfaceMethodOverload(ifc: spec.InterfaceType, overload: spec.Method, _originalMethod: spec.Method) {
this.onInterfaceMethod(ifc, overload);
}
protected onInterfaceProperty(_ifc: spec.InterfaceType, prop: spec.Property) {
const getterType = this.toJavaType(prop.type);
const setterTypes = this.toJavaTypes(prop.type);
const propName = this.code.toPascalCase(prop.name);
// for unions we only generate overloads for setters, not getters.
this.addJavaDocs(prop);
this.code.line(`${getterType} get${propName}();`);
if (!prop.immutable) {
for (const type of setterTypes) {
this.addJavaDocs(prop);
this.code.line(`void set${propName}(final ${type} value);`);
}
}
}
private emitMavenPom(assm: spec.Assembly, fingerprint: boolean) {
const self = this;
if (!(assm.targets && assm.targets.java)) {
throw new Error(`Assembly ${assm.name} does not declare a java target`);
}
const comment = fingerprint
? {
'#comment': [
`Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`,
`@jsii-pacmak:meta@ ${JSON.stringify(this.metadata)}`
]
}
: {};
this.code.openFile('pom.xml');
this.code.line(
xmlbuilder.create({
project: {
'@xmlns': 'http://maven.apache.org/POM/4.0.0',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'@xsi:schemaLocation': 'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd',
...comment,
'modelVersion': '4.0.0',
'name': '${project.groupId}:${project.artifactId}',
'description': assm.description,
'url': assm.homepage,
'licenses': {
license: getLicense()
},
'developers': {
developer: mavenDevelopers()
},
'scm': {
connection: `scm:${assm.repository.type}:${assm.repository.url}`,
url: assm.repository.url
},
...assm.targets.java.maven,
'version': assm.version,
'packaging': 'jar',
'properties': { 'project.build.sourceEncoding': 'UTF-8' },
'dependencies': { dependency: mavenDependencies() },
'build': {
plugins: {
plugin: [{
groupId: 'org.apache.maven.plugins',
artifactId: 'maven-compiler-plugin',
version: '3.6.1',
configuration: { source: '1.8', target: '1.8' }
}, {
groupId: 'org.apache.maven.plugins',
artifactId: 'maven-jar-plugin',
version: '3.1.0',
configuration: {
archive: {
index: true,
manifest: {
addDefaultImplementationEntries: true,
addDefaultSpecificationEntries: true,
}
}
}
}, {
groupId: 'org.apache.maven.plugins',
artifactId: 'maven-source-plugin',
version: '3.0.1',
executions: {
execution: {
id: 'attach-sources',
goals: { goal: 'jar' }
}
}
}, {
groupId: 'org.apache.maven.plugins',
artifactId: 'maven-javadoc-plugin',
version: '3.0.1',
executions: {
execution: {
id: 'attach-javadocs',
goals: { goal: 'jar' }
}
},
configuration: {
failOnError: false,
show: 'protected'
}
}]
}
}
}
}, { encoding: 'UTF-8' }).end({ pretty: true })
);
this.code.closeFile('pom.xml');
function mavenDependencies() {
const dependencies = new Array<MavenDependency>();
const allDeps = { ...(assm.dependencies || {}), ...self.referencedModules };
for (const depName of Object.keys(allDeps)) {
const dep = allDeps[depName];
if (!(dep.targets && dep.targets.java)) {
throw new Error(`Assembly ${assm.name} depends on ${depName}, which does not declare a java target`);
}
dependencies.push({
...dep.targets.java.maven,
version: dep.version
});
}
// The JSII java runtime base classes
dependencies.push({
groupId: 'software.amazon.jsii',
artifactId: 'jsii-runtime',
version: VERSION
});
// Provides @javax.annotation.*
dependencies.push({
groupId: 'javax.annotation',
artifactId: 'javax.annotation-api',
version: '[1.3.2,)',
scope: 'provided'
});
return dependencies;
}
function mavenDevelopers() {
return [assm.author, ...(assm.contributors || [])].map(toDeveloper);
function toDeveloper(person: spec.Person) {
const developer: any = {
[person.organization ? 'organization' : 'name']: person.name,
roles: { role: person.roles }
};
// We cannot set "undefined" or "null" to a field - this causes invalid XML to be emitted (per POM schema).
if (person.email) {
developer.email = person.email;
}
if (person.url) {
developer[person.organization ? 'organizationUrl' : 'url'] = person.url;
}
return developer;
}
}
/**
* Get the maven-style license block for a the assembly.
* @see https://maven.apache.org/pom.html#Licenses
*/
function getLicense() {
const spdx = spdxLicenseList[assm.license];
return spdx && {
name: spdx.name,
url: spdx.url,
distribution: 'repo',
comments: spdx.osiApproved ? 'An OSI-approved license' : undefined
};
}
}
private emitStaticInitializer(cls: spec.ClassType) {
const consts = (cls.properties || []).filter(x => x.const);
if (consts.length === 0) {
return;
}
const javaClass = this.toJavaType(cls);
this.code.openBlock(`static`);
for (const prop of consts) {
const constName = this.renderConstName(prop);
const propClass = this.toJavaType(prop.type, true);
this.code.line(`${constName} = software.amazon.jsii.JsiiObject.jsiiStaticGet(${javaClass}.class, "${prop.name}", ${propClass}.class);`);
}
this.code.closeBlock();
}
private renderConstName(prop: spec.Property) {
return this.code.toSnakeCase(prop.name).toLocaleUpperCase(); // java consts are SNAKE_UPPER_CASE
}
private emitConstProperty(prop: spec.Property) {
const propType = this.toJavaType(prop.type);
const propName = this.renderConstName(prop);
const access = this.renderAccessLevel(prop);
this.addJavaDocs(prop);
this.code.line(`${access} final static ${propType} ${propName};`);
}
private emitProperty(cls: spec.Type, prop: spec.Property, includeGetter = true, overrides: boolean = !!prop.overrides) {
const getterType = this.toJavaType(prop.type);
const setterTypes = this.toJavaTypes(prop.type);
const propClass = this.toJavaType(prop.type, true);
const propName = this.code.toPascalCase(prop.name);
const access = this.renderAccessLevel(prop);
const statc = prop.static ? 'static ' : '';
const javaClass = this.toJavaType(cls);
// for unions we only generate overloads for setters, not getters.
if (includeGetter) {
this.code.line();
this.addJavaDocs(prop);
if (overrides) { this.code.line('@Override'); }
if (prop.type.optional) { this.code.line(JSR305_NULLABLE); }
this.code.openBlock(`${access} ${statc}${getterType} get${propName}()`);
let statement = 'return ';
if (prop.static) {
statement += `software.amazon.jsii.JsiiObject.jsiiStaticGet(${javaClass}.class, `;
} else {
statement += `this.jsiiGet(`;
}
statement += `"${prop.name}", ${propClass}.class);`;
this.code.line(statement);
this.code.closeBlock();
}
if (!prop.immutable) {
for (const type of setterTypes) {
this.code.line();
this.addJavaDocs(prop);
if (overrides) { this.code.line('@Override'); }
const nullable = prop.type.optional ? `${JSR305_NULLABLE} ` : '';
this.code.openBlock(`${access} ${statc}void set${propName}(${nullable}final ${type} value)`);
let statement = '';
if (prop.static) {
statement += `software.amazon.jsii.JsiiObject.jsiiStaticSet(${javaClass}.class, `;
} else {
statement += 'this.jsiiSet(';
}
const value = prop.type.optional ? 'value' : `java.util.Objects.requireNonNull(value, "${prop.name} is required")`;
statement += `"${prop.name}\", ${value});`;
this.code.line(statement);
this.code.closeBlock();
}
}
}
private emitMethod(cls: spec.Type, method: spec.Method, overrides: boolean = !!method.overrides) {
const returnType = method.returns ? this.toJavaType(method.returns) : 'void';
const statc = method.static ? 'static ' : '';
const access = this.renderAccessLevel(method);
const async = !!(method.returns && method.returns.promise);
const methodName = slugify(method.name);
const signature = `${returnType} ${methodName}(${this.renderMethodParameters(method)})`;
this.code.line();
this.addJavaDocs(method);
if (overrides) { this.code.line('@Override'); }
if (method.returns && method.returns.optional) { this.code.line(JSR305_NULLABLE); }
if (method.abstract) {
this.code.line(`${access} abstract ${signature};`);
} else {
this.code.openBlock(`${access} ${statc}${signature}`);
this.code.line(this.renderMethodCall(cls, method, async));
this.code.closeBlock();
}
}
/**
* We are now going to build a class that can be used as a proxy for untyped
* javascript objects that implement this interface. we want java code to be
* able to interact with them, so we will create a proxy class which
* implements this interface and has the same methods.
*/
private emitInterfaceProxy(ifc: spec.InterfaceType | spec.ClassType) {
const name = INTERFACE_PROXY_CLASS_NAME;
this.code.line();
this.code.line('/**');
this.code.line(' * A proxy class which represents a concrete javascript instance of this type.');
this.code.line(' */');
const suffix = ifc.kind === spec.TypeKind.Interface
? `extends software.amazon.jsii.JsiiObject implements ${this.toNativeFqn(ifc.fqn)}`
: `extends ${this.toNativeFqn(ifc.fqn)}`;
this.code.openBlock(`final static class ${name} ${suffix}`);
this.emitJsiiInitializers(name);
// compile a list of all unique methods from the current interface and all
// base interfaces (and their bases).
const methods: { [name: string]: spec.Method } = {};
const properties: { [name: string]: spec.Property } = {};
const collectAbstractMembers = (currentType: spec.InterfaceType | spec.ClassType) => {
for (const prop of currentType.properties || []) {
if (prop.abstract) {
properties[prop.name] = prop;
}
}
for (const method of currentType.methods || []) {
if (method.abstract) {
methods[method.name!] = method;
}
}
const bases = new Array<spec.NamedTypeReference>();
bases.push(...currentType.interfaces || []);
if (currentType.kind === spec.TypeKind.Class && currentType.base) {
bases.push(currentType.base);
}
for (const base of bases) {
const type = this.findType(base.fqn!);
if (type.kind !== spec.TypeKind.Interface && type.kind !== spec.TypeKind.Class) {
throw new Error(`Base interfaces of an interface must be an interface or a class (${base.fqn} is of type ${type.kind})`);
}
collectAbstractMembers(type);
}
};
collectAbstractMembers(ifc);
// emit all properties
for (const propName of Object.keys(properties)) {
const prop = clone(properties[propName]);
prop.abstract = false;
this.emitProperty(ifc, prop, /* includeGetter: */ undefined, /* overrides: */ true);
}
// emit all the methods
for (const methodName of Object.keys(methods)) {
const method = clone(methods[methodName]);
method.abstract = false;
this.emitMethod(ifc, method, /* overrides: */ true);
for (const overloadedMethod of this.createOverloadsForOptionals(method)) {
overloadedMethod.abstract = false;
this.emitMethod(ifc, overloadedMethod, /* overrides: */ true);
}
}
this.code.closeBlock();
}
private emitInterfaceBuilder(ifc: spec.InterfaceType) {
const interfaceName = ifc.name;
const builderName = 'Builder';
this.code.line();
this.code.line('/**');
this.code.line(` * @return a {@link Builder} of {@link ${interfaceName}}`);
this.code.line(' */');
this.code.openBlock(`static ${builderName} builder()`);
this.code.line(`return new ${builderName}();`);
this.code.closeBlock();
interface Prop {
docs?: spec.Docs
spec: spec.Property
propName: string
fieldName: string
fieldJavaType: string
javaTypes: string[]
optional?: boolean
inherited: boolean
immutable: boolean
}
const props = new Array<Prop>();
// collect all properties from all base structs
const self = this;
function collectProps(currentIfc: spec.InterfaceType, isBaseClass = false) {
for (const property of currentIfc.properties || []) {
const propName = self.code.toPascalCase(property.name);
const optional = property.type.optional;
const prop: Prop = {
docs: property.docs,
spec: property,
propName, optional,
fieldName: self.code.toCamelCase(property.name),
fieldJavaType: self.toJavaType(property.type),
javaTypes: self.toJavaTypes(property.type),
immutable: property.immutable || false,
inherited: isBaseClass,
};
props.push(prop);
}
// add props of base struct
for (const base of currentIfc.interfaces || []) {
collectProps(self.findType(base.fqn) as spec.InterfaceType, true);
}
}
collectProps(ifc);
this.code.line();
this.code.line('/**');
this.code.line(` * A builder for {@link ${interfaceName}}`);
this.code.line(' */');
this.code.openBlock(`final class ${builderName}`);
for (const prop of props) {
if (prop.optional) {
this.code.line(JSR305_NULLABLE);
}
this.code.line(`private ${prop.fieldJavaType} _${prop.fieldName};`);
}
this.code.line();
for (const prop of props) {
for (const type of prop.javaTypes) {
this.code.line('/**');
this.code.line(` * Sets the value of ${prop.propName}`);
if (prop.docs && prop.docs.comment) {
this.code.line(` * @param value ${prop.docs.comment}`);
} else {
this.code.line(` * @param value the value to be set`);
}
this.code.line(` * @return {@code this}`);
this.code.line(' */');
this.code.openBlock(`public ${builderName} with${prop.propName}(${prop.optional ? `${JSR305_NULLABLE} ` : ''}final ${type} value)`);
this.code.line(`this._${prop.fieldName} = ${_validateIfNonOptional('value', prop)};`);
this.code.line('return this;');
this.code.closeBlock();
}
}
this.code.line();
this.code.line('/**');
this.code.line(' * Builds the configured instance.');
this.code.line(` * @return a new instance of {@link ${interfaceName}}`);
this.code.line(' * @throws NullPointerException if any required attribute was not provided');
this.code.line(' */');
this.code.openBlock(`public ${interfaceName} build()`);
this.code.openBlock(`return new ${interfaceName}()`);
for (const prop of props) {
if (prop.optional) { this.code.line(JSR305_NULLABLE); }
// tslint:disable-next-line:max-line-length
this.code.line(`private${prop.immutable ? ' final' : ''} ${prop.fieldJavaType} $${prop.fieldName} = ${_validateIfNonOptional(`_${prop.fieldName}`, prop)};`);
}
for (const prop of props) {
this.code.line();
this.code.line('@Override');
this.code.openBlock(`public ${prop.fieldJavaType} get${prop.propName}()`);
this.code.line(`return this.$${prop.fieldName};`);
this.code.closeBlock();
if (!prop.immutable) {
for (const type of prop.javaTypes) {
this.code.line();
this.code.line('@Override');
this.code.openBlock(`public void set${prop.propName}(${prop.optional ? `${JSR305_NULLABLE} ` : ''}final ${type} value)`);
this.code.line(`this.$${prop.fieldName} = ${_validateIfNonOptional('value', prop)};`);
this.code.closeBlock();
}
}
}
// emit $jsii$toJson which will be called to serialize this object when sent to JS
this.code.line();
this.code.openBlock(`public com.fasterxml.jackson.databind.JsonNode $jsii$toJson()`);
this.code.line(`com.fasterxml.jackson.databind.ObjectMapper om = software.amazon.jsii.JsiiObjectMapper.INSTANCE;`);
// tslint:disable-next-line:max-line-length
this.code.line(`com.fasterxml.jackson.databind.node.ObjectNode obj = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();`);
for (const prop of props) {
this.code.line(`obj.set(\"${prop.spec.name}\", om.valueToTree(this.get${prop.propName}()));`);
}
this.code.line(`return obj;`);
this.code.closeBlock();
this.code.unindent();
this.code.line(`};`); /* return new Foo() */
this.code.closeBlock(/* public Foo build() */);
this.code.closeBlock(/* final class Builder */);
function _validateIfNonOptional(variable: string, prop: Prop): string {
if (prop.optional) { return variable; }
return `java.util.Objects.requireNonNull(${variable}, "${prop.fieldName} is required")`;
}
}
private openFileIfNeeded(type: spec.Type) {
if (this.isNested(type)) {
return;
}
this.code.openFile(this.toJavaFilePath(type.fqn));
this.code.line(`package ${this.getNativeName(this.assembly, type.namespace)};`);
this.code.line();
}
private closeFileIfNeeded(type: spec.Type) {
if (this.isNested(type)) {
return;
}
this.code.closeFile(this.toJavaFilePath(type.fqn));
}
private isNested(type: spec.Type) {
if (!this.assembly.types || !type.namespace) { return false; }
const parent = `${type.assembly}.${type.namespace}`;
return parent in this.assembly.types;
}
private toJavaFilePath(fqn: string) {
const nativeFqn = this.toNativeFqn(fqn);
return path.join('src', 'main', 'java', ...nativeFqn.split('.')) + '.java';
}
private addJavaDocs(doc: spec.Documentable, defaultText?: string) {
if (!defaultText && Object.keys(doc.docs || {}).length === 0
&& !((doc as spec.Method).parameters || []).find(p => Object.keys(p.docs || {}).length !== 0)) {
return;
}
doc.docs = doc.docs || { };
this.code.line('/**');
// If there are no docs
if (Object.keys(doc.docs).length === 0 && defaultText) {
this.code.line(` * ${defaultText}`);
}
for (const key of Object.keys(doc.docs)) {
const value = doc.docs[key];
if (key === 'comment') {
value.split('\n').forEach(s => this.code.line(` * ${s}`));
} else {
this.code.line(` * @${key} ${value.replace(/\n/g, ' ')}`);
}
}
// if this is a method, add docs for parameters
if ((doc as spec.Method).parameters) {
const method = doc as spec.Method;
if (method.parameters) {
for (const param of method.parameters) {
if (param.docs && param.docs.comment) {
this.code.line(` * @param ${param.name} ${param.docs.comment}`);
}
}
}
}
this.code.line(' */');
}
private getClassBase(cls: spec.ClassType) {
if (!cls.base) {
return 'software.amazon.jsii.JsiiObject';
}
return this.toJavaType(cls.base);
}
private toJavaType(typeref: spec.TypeReference, forMarshalling = false): string {
const types = this.toJavaTypes(typeref, forMarshalling);
if (types.length > 1) {
return 'java.lang.Object';
} else {
return types[0];
}
}
private toJavaTypes(typeref: spec.TypeReference, forMarshalling = false): string[] {
if (spec.isPrimitiveTypeReference(typeref)) {
return [ this.toJavaPrimitive(typeref.primitive) ];
} else if (spec.isCollectionTypeReference(typeref)) {
return [ this.toJavaCollection(typeref, forMarshalling) ];
} else if (spec.isNamedTypeReference(typeref)) {
return [ this.toNativeFqn(typeref.fqn) ];
} else if (typeref.union) {
const types = new Array<string>();
for (const subtype of typeref.union.types) {
for (const t of this.toJavaTypes(subtype, forMarshalling)) {
types.push(t);
}
}
return types;
} else {
throw new Error('Invalid type reference: ' + JSON.stringify(typeref));
}
}
private toJavaCollection(ref: spec.CollectionTypeReference, forMarshalling: boolean) {
const elementJavaType = this.toJavaType(ref.collection.elementtype);
switch (ref.collection.kind) {
case spec.CollectionKind.Array: return forMarshalling ? 'java.util.List' : `java.util.List<${elementJavaType}>`;
case spec.CollectionKind.Map: return forMarshalling ? 'java.util.Map' : `java.util.Map<java.lang.String, ${elementJavaType}>`;
default:
throw new Error(`Unsupported collection kind: ${ref.collection.kind}`);
}
}
private toJavaPrimitive(primitive: spec.PrimitiveType) {
switch (primitive) {
case spec.PrimitiveType.Boolean: return 'java.lang.Boolean';
case spec.PrimitiveType.Date: return 'java.time.Instant';
case spec.PrimitiveType.Json: return 'com.fasterxml.jackson.databind.node.ObjectNode';
case spec.PrimitiveType.Number: return 'java.lang.Number';
case spec.PrimitiveType.String: return 'java.lang.String';
case spec.PrimitiveType.Any: return 'java.lang.Object';
default:
throw new Error('Unknown primitive type: ' + primitive);
}
}
private renderMethodCallArguments(method: spec.Method) {
if (!method.parameters || method.parameters.length === 0) { return ''; }
let paramStream: string = '';
for (const param of method.parameters) {
const paramValue = param.type.optional ? param.name : `java.util.Objects.requireNonNull(${param.name}, "${param.name} is required")`;
const thisParam = `${param.variadic ? 'java.util.Arrays.stream' : 'java.util.stream.Stream.of'}(${paramValue})`;
if (paramStream === '') {
paramStream = thisParam;
} else {
paramStream = `java.util.stream.Stream.concat(${paramStream}, ${thisParam})`;
}
}
return `, ${paramStream}.toArray()`;
}
private renderMethodCall(cls: spec.TypeReference, method: spec.Method, async: boolean) {
let statement = '';
if (method.returns) {
statement += `return `;
}
if (method.static) {
const javaClass = this.toJavaType(cls);
statement += `software.amazon.jsii.JsiiObject.jsiiStaticCall(${javaClass}.class, `;
} else {
if (async) {
statement += `this.jsiiAsyncCall(`;
} else {
statement += 'this.jsiiCall(';
}
}
statement += `"${method.name}"`;
if (method.returns) {
statement += `, ${this.toJavaType(method.returns, true)}.class`;
} else {
statement += ', Void.class';
}
statement += this.renderMethodCallArguments(method);
statement += ');';