Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New openapi-cli subgenerator for OpenApi client generation #9623

Merged
merged 22 commits into from
Sep 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a6326a1
import swagger cli as sub-generator
ecostanzi Apr 24, 2019
5ce694a
fix openapi-cli index.js to make it work as sub-generator
ecostanzi Apr 24, 2019
e44fa1e
use node openapi-generator-cli instead of jar file
ecostanzi Apr 24, 2019
d14e955
fix iteration over apis to regenerate
ecostanzi Apr 26, 2019
e04e5f5
add openapi-cli command description and USAGE file
ecostanzi Apr 26, 2019
e6cfa45
create promts.js and add generatorName property
ecostanzi May 2, 2019
05727d9
change module name to 'openapi-client'
ecostanzi May 2, 2019
946851c
move writing phases to files.js
ecostanzi May 20, 2019
641d631
generates java files only with spring clients
ecostanzi May 23, 2019
ee30c19
remove package.json openapi-generator, use openapi-generator-cli jar
ecostanzi Jun 20, 2019
68d6a40
add test for openapi-client subgenerator
ecostanzi Jun 20, 2019
0b5c059
fix url composition when reading springfox swagger endpoint list
ecostanzi Jun 20, 2019
af1426b
fix supportingFiles generation and fix test
ecostanzi Jun 20, 2019
c7d29f5
use openapi jar file in the node_modules of the generated project
ecostanzi Jun 20, 2019
807b7b4
fix --regen option
ecostanzi Jun 20, 2019
1d719c9
update openapi-generator-cli to version 0.0.14-4.0.2
ecostanzi Jun 20, 2019
e95a239
test for regeneration and component scan exclusion
ecostanzi Jun 20, 2019
7163192
clean previously generated code before regenerating client
ecostanzi Jun 21, 2019
bfb1256
fix file path validation for custom endpoint
ecostanzi Jun 25, 2019
f96ecbb
fix how the swagger-resources endpoint is built
ecostanzi Jun 25, 2019
2cc6672
use shelljs and lodash instead of fs-extra and underscore.string
ecostanzi Sep 1, 2019
374f578
update package-lock.json
ecostanzi Sep 2, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,17 @@
},
"cwd": "${workspaceFolder}/test-integration/samples/app-sample-dev/",
"console": "integratedTerminal"
}
},
{
"type": "node",
"request": "launch",
"name": "jhipster openapi-client",
"program": "${workspaceFolder}/cli/jhipster.js",
"args": [
"openapi-client"
],
"cwd": "${workspaceFolder}/test-integration/samples/app-sample-dev/",
"console": "integratedTerminal"
},
]
}
3 changes: 3 additions & 0 deletions cli/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ Example:
argument: ['name'],
desc: 'Create a new Spring controller'
},
'openapi-client': {
desc: 'Generates java client code from an OpenAPI/Swagger definition'
},
upgrade: {
desc: 'Upgrade the JHipster version, and upgrade the generated application'
}
Expand Down
1 change: 1 addition & 0 deletions generators/client/templates/angular/package.json.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
<%_ if (protractorTests) { _%>
"webdriver-manager": "12.1.6",
<%_ } _%>
"@openapitools/openapi-generator-cli": "0.0.14-4.0.2",
"webpack": "4.39.3",
"webpack-cli": "3.3.7",
"webpack-dev-server": "3.8.0",
Expand Down
1 change: 1 addition & 0 deletions generators/client/templates/react/package.json.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ limitations under the License.
<%_ if (protractorTests) { _%>
"webdriver-manager": "12.1.5",
<%_ } _%>
"@openapitools/openapi-generator-cli": "0.0.14-4.0.2",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ecostanzi,
It doesn't look appropriate to include generator sub-module dependency in the generated client application. Can't it be encapsulated in the module?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Vishal, what do you mean by saying "encapsulated in the module"?

The documentations suggests:

It is recommended to install the package as development dependency, because normally you only need this dependency during the development process

https://www.npmjs.com/package/@openapitools/openapi-generator-cli#package-mode

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes for me there is no problem to add this as dev dependency. Yes it does add significantly to what you have to download. But as it is useful, I don't see the problem of it being downloaded from npm rather than maven...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, it should be added as generator-jhipster dependency (not under dev) and not in the client applications dev dependency. Can you check if that works?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I'll let you know

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vishal423 I opened issue #10510 to discuss some changes. In that case I think that the dependency should remain in the package.json of the generated project.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ecostanzi, I will leave it to other members to decide. For me, I am planning to create a separate module that wouldn't contain it.

"webpack": "4.28.4",
"webpack-cli": "3.3.0",
"webpack-dev-server": "3.2.1",
Expand Down
5 changes: 5 additions & 0 deletions generators/openapi-client/USAGE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Description:
Generates java client code from an OpenAPI/Swagger definition

Example:
jhipster openapi-client
173 changes: 173 additions & 0 deletions generators/openapi-client/files.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/**
* Copyright 2013-2019 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
*
* http://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.
*/

const path = require('path');
const shelljs = require('shelljs');
const _ = require('lodash');
const chalk = require('chalk');
const jhipsterConstants = require('../generator-constants');

module.exports = {
writeFiles
};

function writeFiles() {
return {
callOpenApiGenerator() {
this.baseName = this.config.get('baseName');
this.authenticationType = this.config.get('authenticationType');
this.packageName = this.config.get('packageName');
this.clientPackageManager = this.config.get('clientPackageManager');
this.packageFolder = this.config.get('packageFolder');
this.buildTool = this.config.get('buildTool');

this.javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;

if (Object.keys(this.clientsToGenerate).length === 0) {
this.log('No openapi client configured. Please run "jhipster openapi-client" to generate your first OpenAPI client.');
return;
}

Object.keys(this.clientsToGenerate).forEach(cliName => {
const inputSpec = this.clientsToGenerate[cliName].spec;
const generatorName = this.clientsToGenerate[cliName].generatorName;

// using openapi jar file since so this section can be tested
const jarPath = path.resolve('node_modules', '@openapitools', 'openapi-generator-cli', 'bin', 'openapi-generator.jar');
let JAVA_OPTS;
let command;
if (generatorName === 'spring') {
this.log(chalk.green(`\n\nGenerating java client code for client ${cliName} (${inputSpec})`));
const cliPackage = `${this.packageName}.client.${_.snakeCase(cliName)}`;
const clientPackageLocation = path.resolve('src', 'main', 'java', ...cliPackage.split('.'));
if (shelljs.test('-d', clientPackageLocation)) {
this.log(`cleanup generated java code for client ${cliName} in directory ${clientPackageLocation}`);
shelljs.rm('-rf', clientPackageLocation);
}

JAVA_OPTS = ' -Dmodels -Dapis -DsupportingFiles=ApiKeyRequestInterceptor.java,ClientConfiguration.java ';

let params =
' generate -g spring ' +
` -t ${path.resolve(__dirname, 'templates/swagger-codegen/libraries/spring-cloud')} ` +
' --library spring-cloud ' +
` -i ${inputSpec} --artifact-id ${_.camelCase(cliName)} --api-package ${cliPackage}.api` +
` --model-package ${cliPackage}.model` +
' --type-mappings DateTime=OffsetDateTime,Date=LocalDate ' +
' --import-mappings OffsetDateTime=java.time.OffsetDateTime,LocalDate=java.time.LocalDate' +
` -DdateLibrary=custom,basePackage=${this.packageName}.client,configPackage=${cliPackage},` +
`title=${_.camelCase(cliName)}`;

if (this.clientsToGenerate[cliName].useServiceDiscovery) {
params += ' --additional-properties ribbon=true';
}

command = `java ${JAVA_OPTS} -jar ${jarPath} ${params}`;
}
this.log(`\n${command}`);

const done = this.async();
shelljs.exec(command, { silent: this.silent }, (code, msg, err) => {
if (code === 0) {
this.success(`Succesfully generated ${cliName} ${generatorName} client`);
done();
} else {
this.error(`Something went wrong while generating ${cliName} ${generatorName} client: ${msg} ${err}`);
done();
}
});
});
},

addBackendDependencies() {
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) {
return;
}

if (this.buildTool === 'maven') {
if (!['microservice', 'gateway', 'uaa'].includes(this.applicationType)) {
let exclusions;
if (this.authenticationType === 'session') {
exclusions =
' <exclusions>\n' +
' <exclusion>\n' +
' <groupId>org.springframework.cloud</groupId>\n' +
' <artifactId>spring-cloud-starter-ribbon</artifactId>\n' +
' </exclusion>\n' +
' </exclusions>';
}
this.addMavenDependency('org.springframework.cloud', 'spring-cloud-starter-openfeign', null, exclusions);
}
this.addMavenDependency('org.springframework.cloud', 'spring-cloud-starter-oauth2');
} else if (this.buildTool === 'gradle') {
if (!['microservice', 'gateway', 'uaa'].includes(this.applicationType)) {
if (this.authenticationType === 'session') {
const content =
"compile 'org.springframework.cloud:spring-cloud-starter-openfeign', { exclude group: 'org.springframework.cloud', module: 'spring-cloud-starter-ribbon' }";
this.rewriteFile('./build.gradle', 'jhipster-needle-gradle-dependency', content);
} else {
this.addGradleDependency('compile', 'org.springframework.cloud', 'spring-cloud-starter-openfeign');
}
}
this.addGradleDependency('compile', 'org.springframework.cloud', 'spring-cloud-starter-oauth2');
}
},

enableFeignClients() {
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) {
return;
}

const mainClassFile = `${this.javaDir + this.getMainClassName()}.java`;

if (this.applicationType !== 'microservice' || !['uaa', 'jwt'].includes(this.authenticationType)) {
this.rewriteFile(
mainClassFile,
'import org.springframework.core.env.Environment;',
'import org.springframework.cloud.openfeign.EnableFeignClients;'
);
this.rewriteFile(mainClassFile, '@SpringBootApplication', '@EnableFeignClients');
}
},

handleComponentScanExclusion() {
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) {
return;
}

const mainClassFile = `${this.javaDir + this.getMainClassName()}.java`;

this.rewriteFile(
mainClassFile,
'import org.springframework.core.env.Environment;',
'import org.springframework.context.annotation.ComponentScan;'
);

const componentScan =
`${'@ComponentScan( excludeFilters = {\n @ComponentScan.Filter('}${this.packageName}` +
'.client.ExcludeFromComponentScan.class)\n})';
this.rewriteFile(mainClassFile, '@SpringBootApplication', componentScan);

this.template(
'src/main/java/package/client/_ExcludeFromComponentScan.java',
`${this.javaDir}/client/ExcludeFromComponentScan.java`
);
}
};
}
94 changes: 94 additions & 0 deletions generators/openapi-client/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* Copyright 2013-2019 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
*
* http://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.
*/

const chalk = require('chalk');
const BaseGenerator = require('../generator-base');
const prompts = require('./prompts');
const writeFiles = require('./files').writeFiles;

module.exports = class extends BaseGenerator {
constructor(args, opts) {
super(args, opts);
this.option('regen', {
desc: 'Regenerates all saved clients',
type: Boolean,
defaults: false
});
this.registerPrettierTransform();
}

get initializing() {
return {
validateFromCli() {
this.checkInvocationFromCLI();
},
sayHello() {
// Have Yeoman greet the user.
this.log(chalk.white('Welcome to the JHipster OpenApi client Sub-Generator'));
},
getConfig() {
this.openApiClients = this.config.get('openApiClients') || {};
}
};
}

get prompting() {
return {
askActionType: prompts.askActionType,
askExistingAvailableDocs: prompts.askExistingAvailableDocs,
askGenerationInfos: prompts.askGenerationInfos
};
}

get configuring() {
return {
determineApisToGenerate() {
this.clientsToGenerate = {};
if (this.options.regen || this.props.action === 'all') {
this.clientsToGenerate = this.openApiClients;
} else if (this.props.action === 'new' || this.props.action === undefined) {
this.clientsToGenerate[this.props.cliName] = {
spec: this.props.inputSpec,
useServiceDiscovery: this.props.useServiceDiscovery,
generatorName: this.props.generatorName
};
} else if (this.props.action === 'select') {
this.props.selected.forEach(selection => {
this.clientsToGenerate[selection.cliName] = selection.spec;
});
}
},

saveConfig() {
if (!this.options.regen && this.props.saveConfig) {
this.openApiClients[this.props.cliName] = this.clientsToGenerate[this.props.cliName];
this.config.set('openApiClients', this.openApiClients);
}
}
};
}

get writing() {
return writeFiles();
}

end() {
this.log('End of openapi-client generator');
}
};
Loading