-
Notifications
You must be signed in to change notification settings - Fork 246
/
java.ts
3688 lines (3337 loc) · 115 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 * as spec from '@jsii/spec';
import * as assert from 'assert';
import * as clone from 'clone';
import { toSnakeCase } from 'codemaker/lib/case-utils';
import { createHash } from 'crypto';
import * as fs from 'fs-extra';
import * as reflect from 'jsii-reflect';
import {
RosettaTabletReader,
TargetLanguage,
enforcesStrictMode,
markDownToJavaDoc,
ApiLocation,
} from 'jsii-rosetta';
import * as path from 'path';
import * as xmlbuilder from 'xmlbuilder';
import { TargetBuilder, BuildOptions } from '../builder';
import { Generator } from '../generator';
import * as logging from '../logging';
import { jsiiToPascalCase } from '../naming-util';
import { JsiiModule } from '../packaging';
import {
PackageInfo,
Target,
findLocalBuildDirs,
TargetOptions,
} from '../target';
import { shell, Scratch, slugify, setExtend } from '../util';
import { VERSION, VERSION_DESC } from '../version';
import { stabilityPrefixFor, renderSummary } from './_utils';
import { toMavenVersionRange, toReleaseVersion } from './version-utils';
import { TargetName } from './index';
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-require-imports
const spdxLicenseList = require('spdx-license-list');
const BUILDER_CLASS_NAME = 'Builder';
const ANN_NOT_NULL = '@org.jetbrains.annotations.NotNull';
const ANN_NULLABLE = '@org.jetbrains.annotations.Nullable';
const ANN_INTERNAL = '@software.amazon.jsii.Internal';
/**
* Build Java packages all together, by generating an aggregate POM
*
* This will make the Java build a lot more efficient (~300%).
*
* Do this by copying the code into a temporary directory, generating an aggregate
* POM there, and then copying the artifacts back into the respective output
* directories.
*/
export class JavaBuilder implements TargetBuilder {
private readonly targetName = 'java';
public constructor(
private readonly modules: readonly JsiiModule[],
private readonly options: BuildOptions,
) {}
public async buildModules(): Promise<void> {
if (this.modules.length === 0) {
return;
}
if (this.options.codeOnly) {
// Simple, just generate code to respective output dirs
await Promise.all(
this.modules.map((module) =>
this.generateModuleCode(
module,
this.options,
this.outputDir(module.outputDirectory),
),
),
);
return;
}
// Otherwise make a single tempdir to hold all sources, build them together and copy them back out
const scratchDirs: Array<Scratch<any>> = [];
try {
const tempSourceDir = await this.generateAggregateSourceDir(
this.modules,
this.options,
);
scratchDirs.push(tempSourceDir);
// Need any old module object to make a target to be able to invoke build, though none of its settings
// will be used.
const target = this.makeTarget(this.modules[0], this.options);
const tempOutputDir = await Scratch.make(async (dir) => {
logging.debug(`Building Java code to ${dir}`);
await target.build(tempSourceDir.directory, dir);
});
scratchDirs.push(tempOutputDir);
await this.copyOutArtifacts(
tempOutputDir.directory,
tempSourceDir.object,
);
if (this.options.clean) {
await Scratch.cleanupAll(scratchDirs);
}
} catch (e) {
logging.warn(
`Exception occurred, not cleaning up ${scratchDirs
.map((s) => s.directory)
.join(', ')}`,
);
throw e;
}
}
private async generateModuleCode(
module: JsiiModule,
options: BuildOptions,
where: string,
): Promise<void> {
const target = this.makeTarget(module, options);
logging.debug(`Generating Java code into ${where}`);
await target.generateCode(where, module.tarball);
}
private async generateAggregateSourceDir(
modules: readonly JsiiModule[],
options: BuildOptions,
): Promise<Scratch<TemporaryJavaPackage[]>> {
return Scratch.make(async (tmpDir: string) => {
logging.debug(`Generating aggregate Java source dir at ${tmpDir}`);
const ret: TemporaryJavaPackage[] = [];
const generatedModules = modules
.map((module) => ({ module, relativeName: slugify(module.name) }))
.map(({ module, relativeName }) => ({
module,
relativeName,
sourceDir: path.join(tmpDir, relativeName),
}))
.map(({ module, relativeName, sourceDir }) =>
this.generateModuleCode(module, options, sourceDir).then(() => ({
module,
relativeName,
})),
);
for (const { module, relativeName } of await Promise.all(
generatedModules,
)) {
ret.push({
relativeSourceDir: relativeName,
relativeArtifactsDir: moduleArtifactsSubdir(module),
outputTargetDirectory: module.outputDirectory,
});
}
await this.generateAggregatePom(
tmpDir,
ret.map((m) => m.relativeSourceDir),
);
await this.generateMavenSettingsForLocalDeps(tmpDir);
return ret;
});
}
private async generateAggregatePom(where: string, moduleNames: string[]) {
const aggregatePom = 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 https://maven.apache.org/xsd/maven-4.0.0.xsd',
'#comment': [
`Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`,
],
modelVersion: '4.0.0',
packaging: 'pom',
groupId: 'software.amazon.jsii',
artifactId: 'aggregatepom',
version: '1.0.0',
modules: {
module: moduleNames,
},
},
},
{ encoding: 'UTF-8' },
)
.end({ pretty: true });
logging.debug(`Generated ${where}/pom.xml`);
await fs.writeFile(path.join(where, 'pom.xml'), aggregatePom);
}
private async copyOutArtifacts(
artifactsRoot: string,
packages: TemporaryJavaPackage[],
) {
logging.debug('Copying out Java artifacts');
// The artifacts directory looks like this:
// /tmp/XXX/software/amazon/awscdk/something/v1.2.3
// /else/v1.2.3
// /entirely/v1.2.3
//
// We get the 'software/amazon/awscdk/something' path from the package, identifying
// the files we need to copy, including Maven metadata. But we need to recreate
// the whole path in the target directory.
await Promise.all(
packages.map(async (pkg) => {
const artifactsSource = path.join(
artifactsRoot,
pkg.relativeArtifactsDir,
);
const artifactsDest = path.join(
this.outputDir(pkg.outputTargetDirectory),
pkg.relativeArtifactsDir,
);
await fs.mkdirp(artifactsDest);
await fs.copy(artifactsSource, artifactsDest, { recursive: true });
}),
);
}
/**
* Decide whether or not to append 'java' to the given output directory
*/
private outputDir(declaredDir: string) {
return this.options.languageSubdirectory
? path.join(declaredDir, this.targetName)
: declaredDir;
}
/**
* Generates maven settings file for this build.
* @param where 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(where: string) {
const filePath = path.join(where, '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 allDepsOutputDirs = new Set<string>();
const resolvedModules = this.modules.map(async (mod) => ({
module: mod,
localBuildDirs: await findLocalBuildDirs(
mod.moduleDirectory,
this.targetName,
),
}));
for (const { module, localBuildDirs } of await Promise.all(
resolvedModules,
)) {
setExtend(allDepsOutputDirs, localBuildDirs);
// Also include output directory where we're building to, in case we build multiple packages into
// the same output directory.
allDepsOutputDirs.add(
path.join(
module.outputDirectory,
this.options.languageSubdirectory ? this.targetName : '',
),
);
}
const localRepos = Array.from(allDepsOutputDirs);
// 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 localRepository = this.options.arguments['maven-local-repository'];
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()}`,
],
// Do *not* attempt to ask the user for stuff...
interactiveMode: false,
// Use a non-default local repository (unless java-custom-cache-path arg is provided) to isolate from cached artifacts...
localRepository: localRepository
? path.resolve(process.cwd(), localRepository)
: path.resolve(where, '.m2', 'repository'),
// Register locations of locally-sourced dependencies
profiles: {
profile: {
id: profileName,
repositories: {
repository: localRepos.map((repo) => ({
id: repo.replace(/[\\/:"<>|?*]/g, '$'),
url: `file://${repo}`,
})),
},
},
},
activeProfiles: {
activeProfile: profileName,
},
},
},
{ encoding: 'UTF-8' },
)
.end({ pretty: true });
logging.debug(`Generated ${filePath}`);
await fs.writeFile(filePath, settings);
return filePath;
}
private makeTarget(module: JsiiModule, options: BuildOptions): Target {
return new Java({
arguments: options.arguments,
assembly: module.assembly,
fingerprint: options.fingerprint,
force: options.force,
packageDir: module.moduleDirectory,
rosetta: options.rosetta,
runtimeTypeChecking: options.runtimeTypeChecking,
targetName: this.targetName,
});
}
}
interface TemporaryJavaPackage {
/**
* Where the sources are (relative to the source root)
*/
relativeSourceDir: string;
/**
* Where the artifacts will be stored after build (relative to build dir)
*/
relativeArtifactsDir: string;
/**
* Where the artifacts ought to go for this particular module
*/
outputTargetDirectory: string;
}
/**
* Return the subdirectory of the output directory where the artifacts for this particular package are produced
*/
function moduleArtifactsSubdir(module: JsiiModule) {
const groupId = module.assembly.targets!.java!.maven.groupId;
const artifactId = module.assembly.targets!.java!.maven.artifactId;
return `${groupId.replace(/\./g, '/')}/${artifactId}`;
}
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 releaseVersion = toReleaseVersion(assm.version, TargetName.JAVA);
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: releaseVersion },
})
.end({ pretty: true })
.replace(/<\?\s*xml(\s[^>]+)?>\s*/m, ''),
},
'Apache Buildr': `'${groupId}:${artifactId}:jar:${releaseVersion}'`,
'Apache Ivy': {
language: 'xml',
code: xmlbuilder
.create({
dependency: {
'@groupId': groupId,
'@name': artifactId,
'@rev': releaseVersion,
},
})
.end({ pretty: true })
.replace(/<\?\s*xml(\s[^>]+)?>\s*/m, ''),
},
'Groovy Grape': `@Grapes(\n@Grab(group='${groupId}', module='${artifactId}', version='${releaseVersion}')\n)`,
'Gradle / Grails': `compile '${groupId}:${artifactId}:${releaseVersion}'`,
},
},
};
}
public static toNativeReference(type: spec.Type, options: any) {
const [, ...name] = type.fqn.split('.');
return { java: `import ${[options.package, ...name].join('.')};` };
}
protected readonly generator: JavaGenerator;
public constructor(options: TargetOptions) {
super(options);
this.generator = new JavaGenerator(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());
}
await shell(
'mvn',
[
// If we don't run in verbose mode, turn on quiet mode
...(this.arguments.verbose ? [] : ['--quiet']),
'--batch-mode',
...mvnArguments,
'deploy',
`-D=altDeploymentRepository=local::default::${url}`,
'--settings=user.xml',
],
{
cwd: sourceDir,
env: {
// Twiddle the JVM settings a little for Maven. Delaying JIT compilation
// brings down Maven execution time by about 1/3rd (15->10s, 30->20s)
MAVEN_OPTS: `${
process.env.MAVEN_OPTS ?? ''
} -XX:+TieredCompilation -XX:TieredStopAtLevel=1`,
},
retry: { maxAttempts: 5 },
},
);
}
}
// ##################
// # CODE GENERATOR #
// ##################
const MODULE_CLASS_NAME = '$Module';
const INTERFACE_PROXY_CLASS_NAME = 'Jsii$Proxy';
const INTERFACE_DEFAULT_CLASS_NAME = 'Jsii$Default';
// Struct that stores metadata about a property that can be used in Java code generation.
interface JavaProp {
// Documentation for the property
docs?: spec.Docs;
// The original JSII property spec this struct was derived from
spec: spec.Property;
// The original JSII type this property was defined on
definingType: spec.Type;
// Canonical name of the Java property (eg: 'MyProperty')
propName: string;
// The original canonical name of the JSII property
jsiiName: string;
// Field name of the Java property (eg: 'myProperty')
fieldName: string;
// The java type for the property (eg: 'List<String>')
fieldJavaType: string;
// The java type for the parameter (e.g: 'List<? extends SomeType>')
paramJavaType: string;
// The NativeType representation of the property's type
fieldNativeType: string;
// The raw class type of the property that can be used for marshalling (eg: 'List.class')
fieldJavaClass: string;
// List of types that the property is assignable from. Used to overload setters.
javaTypes: string[];
// True if the property is optional.
nullable: boolean;
// True if the property has been transitively inherited from a base class.
inherited: boolean;
// True if the property is read-only once initialized.
immutable: boolean;
}
class JavaGenerator extends Generator {
// When the code-generator needs to generate code for a property or method that has the same name as a member of this list, the name will
// be automatically modified to avoid compile errors. Most of these are java language reserved keywords. In addition to those, any keywords that
// are likely to conflict with auto-generated methods or properties (eg: 'build') are also considered reserved.
private static readonly RESERVED_KEYWORDS = [
'abstract',
'assert',
'boolean',
'break',
'build',
'byte',
'case',
'catch',
'char',
'class',
'const',
'continue',
'default',
'double',
'do',
'else',
'enum',
'extends',
'false',
'final',
'finally',
'float',
'for',
'goto',
'if',
'implements',
'import',
'instanceof',
'int',
'interface',
'long',
'native',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'short',
'static',
'strictfp',
'super',
'switch',
'synchronized',
'this',
'throw',
'throws',
'transient',
'true',
'try',
'void',
'volatile',
'while',
'_',
];
/**
* Turns a raw javascript property name (eg: 'default') into a safe Java property name (eg: 'defaultValue').
* @param propertyName the raw JSII property Name
*/
private static safeJavaPropertyName(propertyName: string) {
if (!propertyName) {
return propertyName;
}
if (propertyName === '_') {
// Slightly different pattern for this one
return '__';
}
if (JavaGenerator.RESERVED_KEYWORDS.includes(propertyName)) {
return `${propertyName}Value`;
}
return propertyName;
}
/**
* Turns a raw javascript method name (eg: 'import') into a safe Java method name (eg: 'doImport').
* @param methodName
*/
private static safeJavaMethodName(methodName: string) {
if (!methodName) {
return methodName;
}
if (methodName === '_') {
// Different pattern for this one. Also this should never happen, who names a function '_' ??
return 'doIt';
}
if (JavaGenerator.RESERVED_KEYWORDS.includes(methodName)) {
return `do${jsiiToPascalCase(methodName)}`;
}
return methodName;
}
/** 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.AssemblyConfiguration;
} = {};
private readonly rosetta: RosettaTabletReader;
public constructor(options: {
readonly rosetta: RosettaTabletReader;
readonly runtimeTypeChecking: boolean;
}) {
super({ ...options, generateOverloadsForMethodWithOptionals: true });
this.rosetta = options.rosetta;
}
protected onBeginAssembly(assm: spec.Assembly, fingerprint: boolean) {
this.emitFullGeneratorInfo = fingerprint;
this.moduleClass = this.emitModuleFile(assm);
this.emitAssemblyPackageInfo(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, { api: 'type', fqn: cls.fqn });
const classBase = this.getClassBase(cls);
const extendsExpression = classBase ? ` extends ${classBase}` : '';
let implementsExpr = '';
if (cls.interfaces?.length ?? 0 > 0) {
implementsExpr = ` implements ${cls
.interfaces!.map((x) => this.toNativeFqn(x))
.join(', ')}`;
}
const nested = this.isNested(cls);
const inner = nested ? ' static' : '';
const absPrefix = abstract ? ' abstract' : '';
if (!nested) {
this.emitGeneratedAnnotation();
}
this.emitStabilityAnnotations(cls);
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);
this.emitStaticInitializer(cls);
}
protected onEndClass(cls: spec.ClassType) {
if (cls.abstract) {
const type = this.reflectAssembly.findType(cls.fqn) as reflect.ClassType;
this.emitProxy(type);
} else {
this.emitClassBuilder(cls);
}
this.code.closeBlock();
this.closeFileIfNeeded(cls);
}
protected onInitializer(cls: spec.ClassType, method: spec.Initializer) {
this.code.line();
// If needed, patching up the documentation to point users at the builder pattern
this.addJavaDocs(method, { api: 'initializer', fqn: cls.fqn });
this.emitStabilityAnnotations(method);
// Abstract classes should have protected initializers
const initializerAccessLevel = cls.abstract
? 'protected'
: this.renderAccessLevel(method);
this.code.openBlock(
`${initializerAccessLevel} ${cls.name}(${this.renderMethodParameters(
method,
)})`,
);
this.code.line(
'super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);',
);
this.emitUnionParameterValdation(method.parameters);
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);
}
protected onField(
_cls: spec.ClassType,
_prop: spec.Property,
_union?: spec.UnionTypeReference,
) {
/* noop */
}
protected onProperty(cls: spec.ClassType, prop: spec.Property) {
this.emitProperty(cls, prop, cls);
}
protected onStaticProperty(cls: spec.ClassType, prop: spec.Property) {
if (prop.const) {
this.emitConstProperty(cls, prop);
} else {
this.emitProperty(cls, prop, cls);
}
}
/**
* 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, cls);
}
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, { api: 'type', fqn: enm.fqn });
if (!this.isNested(enm)) {
this.emitGeneratedAnnotation();
}
this.emitStabilityAnnotations(enm);
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(parentType: spec.EnumType, member: spec.EnumMember) {
this.addJavaDocs(member, {
api: 'member',
fqn: parentType.fqn,
memberName: member.name,
});
this.emitStabilityAnnotations(member);
this.code.line(`${member.name},`);
}
/**
* Namespaces are handled implicitly by onBeginClass().
*
* Only emit package-info in case this is a submodule
*/
protected onBeginNamespace(ns: string) {
const submodule = this.assembly.submodules?.[ns];
if (submodule) {
this.emitSubmodulePackageInfo(this.assembly, ns);
}
}
protected onEndNamespace(_ns: string) {
/* noop */
}
protected onBeginInterface(ifc: spec.InterfaceType) {
this.openFileIfNeeded(ifc);
this.addJavaDocs(ifc, { api: 'type', fqn: ifc.fqn });
// 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)),
].join(', ');
const nested = this.isNested(ifc);
const inner = nested ? ' static' : '';
if (!nested) {
this.emitGeneratedAnnotation();
}
this.code.line(
`@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${ifc.fqn}")`,
);
this.code.line(
`@software.amazon.jsii.Jsii.Proxy(${ifc.name}.${INTERFACE_PROXY_CLASS_NAME}.class)`,
);
this.emitStabilityAnnotations(ifc);
this.code.openBlock(
`public${inner} interface ${ifc.name} extends ${bases}`,
);
}
protected onEndInterface(ifc: spec.InterfaceType) {
this.emitMultiplyInheritedOptionalProperties(ifc);
if (ifc.datatype) {
this.emitDataType(ifc);
} else {
const type = this.reflectAssembly.findType(
ifc.fqn,
) as reflect.InterfaceType;
this.emitProxy(type);
// We don't emit Jsii$Default if the assembly opted out of it explicitly.
// This is mostly to facilitate compatibility testing...
if (hasDefaultInterfaces(this.reflectAssembly)) {
this.emitDefaultImplementation(type);
}
}
this.code.closeBlock();
this.closeFileIfNeeded(ifc);
}
protected onInterfaceMethod(ifc: spec.InterfaceType, method: spec.Method) {
this.code.line();
const returnType = method.returns
? this.toDecoratedJavaType(method.returns)
: 'void';
const methodName = JavaGenerator.safeJavaMethodName(method.name);
this.addJavaDocs(method, {
api: 'member',
fqn: ifc.fqn,
memberName: methodName,
});
this.emitStabilityAnnotations(method);
this.code.line(
`${returnType} ${methodName}(${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.toDecoratedJavaType(prop);
const propName = jsiiToPascalCase(
JavaGenerator.safeJavaPropertyName(prop.name),
);
// for unions we only generate overloads for setters, not getters.
this.code.line();
this.addJavaDocs(prop, {
api: 'member',
fqn: ifc.fqn,
memberName: prop.name,
});
this.emitStabilityAnnotations(prop);
if (prop.optional) {
if (prop.overrides) {
this.code.line('@Override');
}
this.code.openBlock(`default ${getterType} get${propName}()`);
this.code.line('return null;');
this.code.closeBlock();
} else {
this.code.line(`${getterType} get${propName}();`);
}
if (!prop.immutable) {
const setterTypes = this.toDecoratedJavaTypes(prop);
for (const type of setterTypes) {
this.code.line();
this.addJavaDocs(prop, {
api: 'member',
fqn: ifc.fqn,
memberName: prop.name,
});
if (prop.optional) {
if (prop.overrides) {
this.code.line('@Override');
}
this.code.line('@software.amazon.jsii.Optional');
this.code.openBlock(
`default void set${propName}(final ${type} value)`,
);
this.code.line(
`throw new UnsupportedOperationException("'void " + getClass().getCanonicalName() + "#set${propName}(${type})' is not implemented!");`,
);
this.code.closeBlock();
} else {
this.code.line(`void set${propName}(final ${type} value);`);
}
}
}
}
/**
* Emits a local default implementation for optional properties inherited from
* multiple distinct parent types. This remvoes the default method dispatch
* ambiguity that would otherwise exist.
*
* @param ifc the interface to be processed.
*
* @see https://github.com/aws/jsii/issues/2256
*/
private emitMultiplyInheritedOptionalProperties(ifc: spec.InterfaceType) {
if (ifc.interfaces == null || ifc.interfaces.length <= 1) {
// Nothing to do if we don't have parent interfaces, or if we have exactly one
return;
}
const inheritedOptionalProps = ifc.interfaces
.map(allOptionalProps.bind(this))
// Calculate how many direct parents brought a given optional property
.reduce(
(histogram, entry) => {
for (const [name, spec] of Object.entries(entry)) {
histogram[name] = histogram[name] ?? { spec, count: 0 };
histogram[name].count += 1;
}
return histogram;
},
{} as Record<string, { readonly spec: spec.Property; count: number }>,