Skip to content

Commit

Permalink
Merge pull request #23732 from mshima/skip_ci-java
Browse files Browse the repository at this point in the history
move entities and enums to the java generator
  • Loading branch information
DanielFran authored Oct 6, 2023
2 parents 424ebb1 + a80f7f3 commit 3d244c2
Show file tree
Hide file tree
Showing 17 changed files with 816 additions and 69 deletions.
4 changes: 3 additions & 1 deletion generators/base-core/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOpti
}

Object.entries(options ?? {})
.concat(Object.entries(configs).map(([name, def]) => [name, convertConfigToOption(name, def)]))
.concat(Object.entries(configs).map(([name, def]) => [name, convertConfigToOption(name, def)]) as any)
.forEach(([optionName, optionDesc]) => {
if (!optionDesc?.type || !optionDesc.scope || (common && optionDesc.scope === 'generator')) return;
let optionValue;
Expand All @@ -314,6 +314,8 @@ export default class CoreGenerator extends YeomanGenerator<JHipsterGeneratorOpti
} else {
throw new Error(`Scope ${optionDesc.scope} not supported`);
}
} else if (optionDesc.default && optionDesc.scope === 'generator' && this[optionName] === undefined) {
this[optionName] = optionDesc.default;
}
});
}
Expand Down
5 changes: 4 additions & 1 deletion generators/base/api.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,13 @@ export type WriteFileOptions<Generator = CoreGenerator, DataType = any> = {
}
);

export type JHispterChoices = string[] | { value: string; name: string }[];

export type JHipsterOption = SetOptional<CliOptionSpec, 'name'> & {
name?: string;
scope?: 'storage' | 'blueprint' | 'control' | 'generator';
env?: string;
choices?: JHispterChoices;
};

export type ValidationResult = {
Expand All @@ -185,7 +188,7 @@ export type JHipsterArgumentConfig = SetOptional<ArgumentSpec, 'name'> & { scope

export type ConfigSpec = {
description?: string;
choices?: string[] | { value: string; name: string }[];
choices?: JHispterChoices;

cli?: SetOptional<CliOptionSpec, 'name'>;
argument?: JHipsterArgumentConfig;
Expand Down
18 changes: 18 additions & 0 deletions generators/java/__snapshots__/generator.spec.mts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,32 @@

exports[`generator - java with default config should match files snapshot 1`] = `
{
".jhipster/Foo.json": {
"stateCleared": "modified",
},
".yo-rc.json": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/GeneratedByJHipster.java": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/domain/Foo.java": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/domain/enumeration/MyEnum.java": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/domain/enumeration/package-info.java": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/domain/package-info.java": {
"stateCleared": "modified",
},
"src/main/java/com/mycompany/myapp/package-info.java": {
"stateCleared": "modified",
},
"src/test/java/com/mycompany/myapp/domain/FooTest.java": {
"stateCleared": "modified",
},
}
`;
19 changes: 19 additions & 0 deletions generators/java/command.mts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,25 @@ const command: JHipsterCommandDefinition = {
packageInfoFile: {
description: 'write package-info.java file for every package',
type: Boolean,
default: true,
scope: 'generator',
hide: true,
},
generateEntities: {
type: Boolean,
default: true,
scope: 'generator',
hide: true,
},
useJakartaValidation: {
type: Boolean,
default: true,
scope: 'generator',
hide: true,
},
generateEnums: {
type: Boolean,
default: true,
scope: 'generator',
hide: true,
},
Expand Down
48 changes: 48 additions & 0 deletions generators/java/entity-files.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Copyright 2013-2023 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { WriteFileSection } from '../base/api.mjs';
import { javaMainPackageTemplatesBlock, javaTestPackageTemplatesBlock } from './support/index.mjs';

export const entityServerFiles: WriteFileSection = {
model: [
javaMainPackageTemplatesBlock({
templates: ['_entityPackage_/domain/_persistClass_.java.jhi'],
}),
],
modelTestFiles: [
javaTestPackageTemplatesBlock({
templates: ['_entityPackage_/domain/_persistClass_Test.java'],
}),
],
server: [
javaMainPackageTemplatesBlock({
condition: ctx => ctx.useJakartaValidation,
templates: ['_entityPackage_/domain/_persistClass_.java.jhi.jakarta_validation'],
}),
],
};

export const enumFiles: WriteFileSection = {
enumFiles: [
javaMainPackageTemplatesBlock({
renameTo: (data, filepath) => filepath.replace('_enumName_', data.enumName),
templates: ['_entityPackage_/domain/enumeration/_enumName_.java'],
}),
],
};
50 changes: 48 additions & 2 deletions generators/java/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,17 @@ import { GenericSourceTypeDefinition } from '../base/tasks.mjs';
import command from './command.mjs';
import { JAVA_COMPATIBLE_VERSIONS } from '../generator-constants.mjs';
import { matchMainJavaFiles } from './support/package-info-transform.mjs';
import { entityServerFiles, enumFiles } from './entity-files.mjs';
import { getEnumInfo } from '../base-application/support/index.mjs';

export type ApplicationDefinition = GenericApplicationDefinition<JavaApplication>;
export type GeneratorDefinition = BaseApplicationGeneratorDefinition<ApplicationDefinition & GenericSourceTypeDefinition>;

export default class JavaGenerator extends BaseApplicationGenerator<GeneratorDefinition> {
packageInfoFile = true;
packageInfoFile!: boolean;
generateEntities!: boolean;
useJakartaValidation!: boolean;
generateEnums!: boolean;

async beforeQueue() {
if (!this.fromBlueprint) {
Expand All @@ -49,7 +54,7 @@ export default class JavaGenerator extends BaseApplicationGenerator<GeneratorDef
get initializing() {
return this.asInitializingTaskGroup({
loadConfig() {
this.parseJHipsterOptions(command.options);
this.parseJHipsterCommand(command);
},

validateJava() {
Expand Down Expand Up @@ -118,6 +123,47 @@ export default class JavaGenerator extends BaseApplicationGenerator<GeneratorDef
return this.delegateTasksToBlueprint(() => this.writing);
}

get writingEntities() {
return this.asWritingEntitiesTaskGroup({
async writeServerFiles({ application, entities }) {
if (!this.generateEntities) return;

const { useJakartaValidation } = this;
for (const entity of entities.filter(entity => !entity.skipServer && !entity.builtIn)) {
await this.writeFiles({
sections: entityServerFiles,
context: { ...application, ...entity, useJakartaValidation },
});
}
},

async writeEnumFiles({ application, entities }) {
if (!this.generateEnums || !this.generateEntities) return;

for (const entity of entities.filter(entity => !entity.skipServer)) {
for (const field of entity.fields.filter(field => field.fieldIsEnum)) {
const enumInfo = {
...getEnumInfo(field, (entity as any).clientRootFolder),
frontendAppName: (entity as any).frontendAppName,
packageName: application.packageName,
javaPackageSrcDir: application.javaPackageSrcDir,
entityJavaPackageFolder: (entity as any).entityJavaPackageFolder,
entityAbsolutePackage: (entity as any).entityAbsolutePackage || application.packageName,
};
await this.writeFiles({
sections: enumFiles,
context: enumInfo,
});
}
}
},
});
}

get [BaseApplicationGenerator.WRITING_ENTITIES]() {
return this.delegateTasksToBlueprint(() => this.writingEntities);
}

/**
* Check if a supported Java is installed
*
Expand Down
94 changes: 93 additions & 1 deletion generators/java/generator.spec.mts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,103 @@ describe(`generator - ${generator}`, () => {

describe('with default config', () => {
before(async () => {
await helpers.runJHipster(GENERATOR_JAVA).withJHipsterConfig();
await helpers.runJHipster(GENERATOR_JAVA).withJHipsterConfig({}, [
{
name: 'Foo',
fields: [
{ fieldName: 'name', fieldType: 'String', fieldValidateRules: ['required'] },
{ fieldName: 'myEnum', fieldType: 'MyEnum', fieldValues: 'FRENCH,ENGLISH' },
],
},
]);
});

it('should match files snapshot', () => {
expect(result.getStateSnapshot()).toMatchSnapshot();
});

it('should generate entities containing jakarta', () => {
result.assertFileContent('src/main/java/com/mycompany/myapp/domain/Foo.java.jhi', 'jakarta');
});

it('should write enum files', () => {
result.assertFile('src/main/java/com/mycompany/myapp/domain/enumeration/MyEnum.java');
expect(Object.keys(result.getStateSnapshot('**/enumeration/**')).length).toBe(2);
});

it('should have options defaults set', () => {
expect(result.generator.generateEntities).toBe(true);
expect(result.generator.generateEnums).toBe(true);
expect(result.generator.useJakartaValidation).toBe(true);
});
});

describe('with jakarta and enums disabled', () => {
before(async () => {
await helpers
.runJHipster(GENERATOR_JAVA)
.withJHipsterConfig({}, [
{
name: 'Foo',
fields: [
{ fieldName: 'name', fieldType: 'String', fieldValidateRules: ['required'] },
{ fieldName: 'myEnum', fieldType: 'MyEnum', fieldValues: 'FRENCH,ENGLISH' },
],
},
])
.withOptions({ useJakartaValidation: false, generateEnums: false });
});

it('should generate entities not containing jakarta', () => {
result.assertNoFileContent('src/main/java/com/mycompany/myapp/domain/Foo.java.jhi', 'jakarta');
});

it('should not write enum files', () => {
expect(Object.keys(result.getStateSnapshot('**/enumeration/**')).length).toBe(0);
});
});

describe('with entities disabled', () => {
before(async () => {
await helpers
.runJHipster(GENERATOR_JAVA)
.withJHipsterConfig({}, [
{
name: 'Foo',
fields: [
{ fieldName: 'name', fieldType: 'String', fieldValidateRules: ['required'] },
{ fieldName: 'myEnum', fieldType: 'MyEnum', fieldValues: 'FRENCH,ENGLISH' },
],
},
])
.withOptions({ generateEntities: false });
});

it('should not contain jakarta', () => {
result.assertNoFile('src/main/java/com/mycompany/myapp/domain/Foo.java.jhi');
});

it('should not write enum files', () => {
expect(Object.keys(result.getStateSnapshot('**/enumeration/**')).length).toBe(0);
});
});

describe('with custom properties values', () => {
before(async () => {
await helpers
.runJHipster(GENERATOR_JAVA)
.withJHipsterConfig({})
.onGenerator(generator => {
generator.generateEntities = false;
generator.generateEnums = false;
generator.useJakartaValidation = false;
});
});

it('should not override custom values', () => {
expect(result.generator.generateEntities).toBe(false);
expect(result.generator.generateEnums).toBe(false);
expect(result.generator.useJakartaValidation).toBe(false);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import jakarta.validation.constraints.*;
<%_ for (const field of fields) { _%>
<&_ if (fragment.field<%- field.fieldNameCapitalized %>AnnotationSection) { -&>
<%_ if (field.fieldValidate === true) { -%>
<%- include('../_partials_entity_/field_validators', {field, reactive}); -%>
<%- include('/_global_partials_entity_/field_validators', {field, reactive}); -%>
<%_ } _%>
<&_ } -&>
<%_ } -%>
Expand Down
Loading

0 comments on commit 3d244c2

Please sign in to comment.