Skip to content

Commit

Permalink
Merge pull request #9623 from ecostanzi/openapi-cli
Browse files Browse the repository at this point in the history
New openapi-cli subgenerator for OpenApi client generation
  • Loading branch information
DanielFran authored Sep 5, 2019
2 parents 4277d58 + 374f578 commit 1bc7b60
Show file tree
Hide file tree
Showing 20 changed files with 1,086 additions and 3 deletions.
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 @@ -147,6 +147,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 @@ -166,6 +166,7 @@ limitations under the License.
<%_ if (protractorTests) { _%>
"webdriver-manager": "12.1.5",
<%_ } _%>
"@openapitools/openapi-generator-cli": "0.0.14-4.0.2",
"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

0 comments on commit 1bc7b60

Please sign in to comment.