forked from loafle/openapi-generator-original
adding Intellij style xml and applied to all java code (#20734)
* added intellij-codestyle.xml and sample of it being applied to some java code-gen classes * code-format changes ONLY * few more format changes since last merge with master * applied code-style to all java one last time
This commit is contained in:
parent
3ad5303f99
commit
2cff152e2a
9
intellij-codestyle.xml
Normal file
9
intellij-codestyle.xml
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<code_scheme name="Project" version="173">
|
||||||
|
<JavaCodeStyleSettings>
|
||||||
|
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION" value="true" />
|
||||||
|
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION_IN_PARAMETER" value="true" />
|
||||||
|
</JavaCodeStyleSettings>
|
||||||
|
<codeStyleSettings language="JAVA">
|
||||||
|
<option name="FIELD_ANNOTATION_WRAP" value="0" />
|
||||||
|
</codeStyleSettings>
|
||||||
|
</code_scheme>
|
@ -1,7 +1,8 @@
|
|||||||
package org.openapitools.codegen;
|
package org.openapitools.codegen;
|
||||||
|
|
||||||
public class Constants {
|
public class Constants {
|
||||||
private Constants(){ }
|
private Constants() {
|
||||||
|
}
|
||||||
|
|
||||||
public static final String CLI_NAME = "openapi-generator-cli";
|
public static final String CLI_NAME = "openapi-generator-cli";
|
||||||
public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator";
|
public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator";
|
||||||
|
@ -138,7 +138,7 @@ public class AuthorTemplate extends OpenApiGeneratorCommand {
|
|||||||
} else {
|
} else {
|
||||||
LOGGER.warn("The library filter '{}' extracted an unexpected library path: {}", library, p.toAbsolutePath());
|
LOGGER.warn("The library filter '{}' extracted an unexpected library path: {}", library, p.toAbsolutePath());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
LOGGER.info("Extracted templates to '{}' directory. Refer to https://openapi-generator.tech/docs/templating for customization details.", outputDirPath);
|
LOGGER.info("Extracted templates to '{}' directory. Refer to https://openapi-generator.tech/docs/templating for customization details.", outputDirPath);
|
||||||
|
@ -20,11 +20,7 @@ package org.openapitools.codegen.cmd;
|
|||||||
import io.airlift.airline.Command;
|
import io.airlift.airline.Command;
|
||||||
import io.airlift.airline.Option;
|
import io.airlift.airline.Option;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.openapitools.codegen.CliOption;
|
import org.openapitools.codegen.*;
|
||||||
import org.openapitools.codegen.CodegenConfig;
|
|
||||||
import org.openapitools.codegen.CodegenConfigLoader;
|
|
||||||
import org.openapitools.codegen.GeneratorNotFoundException;
|
|
||||||
import org.openapitools.codegen.VendorExtension;
|
|
||||||
import org.openapitools.codegen.meta.FeatureSet;
|
import org.openapitools.codegen.meta.FeatureSet;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -37,10 +33,10 @@ import java.util.concurrent.atomic.AtomicReference;
|
|||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
|
|
||||||
import static org.apache.commons.lang3.StringUtils.isEmpty;
|
import static org.apache.commons.lang3.StringUtils.isEmpty;
|
||||||
|
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
|
||||||
|
|
||||||
@SuppressWarnings({"unused","java:S106", "java:S1192"})
|
@SuppressWarnings({"unused", "java:S106", "java:S1192"})
|
||||||
@Command(name = "config-help", description = "Config help for chosen lang")
|
@Command(name = "config-help", description = "Config help for chosen lang")
|
||||||
public class ConfigHelp extends OpenApiGeneratorCommand {
|
public class ConfigHelp extends OpenApiGeneratorCommand {
|
||||||
|
|
||||||
@ -49,7 +45,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
|||||||
private static final String FORMAT_TEXT = "text";
|
private static final String FORMAT_TEXT = "text";
|
||||||
private static final String FORMAT_MARKDOWN = "markdown";
|
private static final String FORMAT_MARKDOWN = "markdown";
|
||||||
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
|
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
|
||||||
private static final int FEATURE_SET_DISPLAY_WIDTH= 20;
|
private static final int FEATURE_SET_DISPLAY_WIDTH = 20;
|
||||||
|
|
||||||
@Option(name = {"-g",
|
@Option(name = {"-g",
|
||||||
"--generator-name"}, title = "generator name", description = "generator to get config help for")
|
"--generator-name"}, title = "generator name", description = "generator to get config help for")
|
||||||
@ -121,7 +117,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
|||||||
private Boolean markdownHeader;
|
private Boolean markdownHeader;
|
||||||
|
|
||||||
@Option(name = {
|
@Option(name = {
|
||||||
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
|
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
|
||||||
private Boolean supportedVendorExtensions;
|
private Boolean supportedVendorExtensions;
|
||||||
|
|
||||||
@Option(name = {"--full-details"}, title = "full generator details", description = "displays CLI options as well as other configs/mappings (implies --instantiation-types, --reserved-words, --language-specific-primitives, --import-mappings, --feature-set)")
|
@Option(name = {"--full-details"}, title = "full generator details", description = "displays CLI options as well as other configs/mappings (implies --instantiation-types, --reserved-words, --language-specific-primitives, --import-mappings, --feature-set)")
|
||||||
@ -241,16 +237,16 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sb
|
sb
|
||||||
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
|
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
|
||||||
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
|
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
|
||||||
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
|
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
|
||||||
|
|
||||||
supportedVendorExtensions.forEach(
|
supportedVendorExtensions.forEach(
|
||||||
extension -> sb.append("|").append(extension.getName())
|
extension -> sb.append("|").append(extension.getName())
|
||||||
.append("|").append(extension.getDescription())
|
.append("|").append(extension.getDescription())
|
||||||
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
|
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
|
||||||
.append("|").append(extension.getDefaultValue())
|
.append("|").append(extension.getDefaultValue())
|
||||||
.append(newline)
|
.append(newline)
|
||||||
);
|
);
|
||||||
sb.append(newline);
|
sb.append(newline);
|
||||||
}
|
}
|
||||||
@ -359,17 +355,17 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
|
|||||||
|
|
||||||
sb.append("| Property | Value | Notes |").append(newline);
|
sb.append("| Property | Value | Notes |").append(newline);
|
||||||
sb.append("| -------- | ----- | ----- |").append(newline);
|
sb.append("| -------- | ----- | ----- |").append(newline);
|
||||||
sb.append("| generator name | "+config.getName()+" | pass this to the generate command after -g |").append(newline);
|
sb.append("| generator name | " + config.getName() + " | pass this to the generate command after -g |").append(newline);
|
||||||
sb.append("| generator stability | "+config.getGeneratorMetadata().getStability()+" | |").append(newline);
|
sb.append("| generator stability | " + config.getGeneratorMetadata().getStability() + " | |").append(newline);
|
||||||
sb.append("| generator type | "+config.getTag()+" | |").append(newline);
|
sb.append("| generator type | " + config.getTag() + " | |").append(newline);
|
||||||
if (config.generatorLanguage() != null) {
|
if (config.generatorLanguage() != null) {
|
||||||
sb.append("| generator language | "+config.generatorLanguage().toString()+" | |").append(newline);
|
sb.append("| generator language | " + config.generatorLanguage().toString() + " | |").append(newline);
|
||||||
}
|
}
|
||||||
if (config.generatorLanguageVersion() != null) {
|
if (config.generatorLanguageVersion() != null) {
|
||||||
sb.append("| generator language version | "+config.generatorLanguageVersion()+" | |").append(newline);
|
sb.append("| generator language version | " + config.generatorLanguageVersion() + " | |").append(newline);
|
||||||
}
|
}
|
||||||
sb.append("| generator default templating engine | "+config.defaultTemplatingEngine()+" | |").append(newline);
|
sb.append("| generator default templating engine | " + config.defaultTemplatingEngine() + " | |").append(newline);
|
||||||
sb.append("| helpTxt | "+config.getHelp()+" | |").append(newline);
|
sb.append("| helpTxt | " + config.getHelp() + " | |").append(newline);
|
||||||
|
|
||||||
sb.append(newline);
|
sb.append(newline);
|
||||||
}
|
}
|
||||||
|
@ -17,18 +17,10 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen.cmd;
|
package org.openapitools.codegen.cmd;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
|
|
||||||
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
|
|
||||||
|
|
||||||
import ch.qos.logback.classic.LoggerContext;
|
import ch.qos.logback.classic.LoggerContext;
|
||||||
import ch.qos.logback.core.spi.FilterAttachable;
|
import ch.qos.logback.core.spi.FilterAttachable;
|
||||||
import io.airlift.airline.Command;
|
import io.airlift.airline.Command;
|
||||||
import io.airlift.airline.Option;
|
import io.airlift.airline.Option;
|
||||||
import java.io.File;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.openapitools.codegen.*;
|
import org.openapitools.codegen.*;
|
||||||
import org.openapitools.codegen.config.CodegenConfigurator;
|
import org.openapitools.codegen.config.CodegenConfigurator;
|
||||||
@ -36,6 +28,14 @@ import org.openapitools.codegen.config.MergedSpecBuilder;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
|
||||||
|
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
|
||||||
|
|
||||||
@SuppressWarnings({"java:S106"})
|
@SuppressWarnings({"java:S106"})
|
||||||
@Command(name = "generate", description = "Generate code with the specified generator.")
|
@Command(name = "generate", description = "Generate code with the specified generator.")
|
||||||
public class Generate extends OpenApiGeneratorCommand {
|
public class Generate extends OpenApiGeneratorCommand {
|
||||||
@ -101,7 +101,7 @@ public class Generate extends OpenApiGeneratorCommand {
|
|||||||
+ "overwritten during the generation.")
|
+ "overwritten during the generation.")
|
||||||
private Boolean skipOverwrite;
|
private Boolean skipOverwrite;
|
||||||
|
|
||||||
@Option(name = { "--dry-run" }, title = "Dry run",
|
@Option(name = {"--dry-run"}, title = "Dry run",
|
||||||
description = "Try things out and report on potential changes (without actually making changes).")
|
description = "Try things out and report on potential changes (without actually making changes).")
|
||||||
private Boolean isDryRun;
|
private Boolean isDryRun;
|
||||||
|
|
||||||
@ -327,15 +327,15 @@ public class Generate extends OpenApiGeneratorCommand {
|
|||||||
private Boolean legacyDiscriminatorBehavior;
|
private Boolean legacyDiscriminatorBehavior;
|
||||||
|
|
||||||
@Option(name = {"--minimal-update"},
|
@Option(name = {"--minimal-update"},
|
||||||
title = "Minimal update",
|
title = "Minimal update",
|
||||||
description = "Only write output files that have changed.")
|
description = "Only write output files that have changed.")
|
||||||
private Boolean minimalUpdate;
|
private Boolean minimalUpdate;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void execute() {
|
public void execute() {
|
||||||
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
|
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
|
||||||
spec = new MergedSpecBuilder(inputSpecRootDirectory, StringUtils.isBlank(mergedFileName) ? "_merged_spec" : mergedFileName)
|
spec = new MergedSpecBuilder(inputSpecRootDirectory, StringUtils.isBlank(mergedFileName) ? "_merged_spec" : mergedFileName)
|
||||||
.buildMergedSpec();
|
.buildMergedSpec();
|
||||||
System.out.println("Merge input spec would be used - " + spec);
|
System.out.println("Merge input spec would be used - " + spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -18,7 +18,6 @@ package org.openapitools.codegen.cmd;
|
|||||||
|
|
||||||
import ch.qos.logback.classic.Level;
|
import ch.qos.logback.classic.Level;
|
||||||
import ch.qos.logback.classic.LoggerContext;
|
import ch.qos.logback.classic.LoggerContext;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonParser;
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
import com.fasterxml.jackson.core.JsonToken;
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
import com.fasterxml.jackson.databind.*;
|
import com.fasterxml.jackson.databind.*;
|
||||||
@ -26,7 +25,6 @@ import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
|
|||||||
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
|
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
|
||||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||||
import com.fasterxml.jackson.databind.util.TokenBuffer;
|
import com.fasterxml.jackson.databind.util.TokenBuffer;
|
||||||
|
|
||||||
import io.airlift.airline.Arguments;
|
import io.airlift.airline.Arguments;
|
||||||
import io.airlift.airline.Command;
|
import io.airlift.airline.Command;
|
||||||
import io.airlift.airline.Option;
|
import io.airlift.airline.Option;
|
||||||
@ -211,7 +209,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
|
|||||||
ClientOptInput opts = configurator.toClientOptInput();
|
ClientOptInput opts = configurator.toClientOptInput();
|
||||||
CodegenConfig config = opts.getConfig();
|
CodegenConfig config = opts.getConfig();
|
||||||
name = config.getName();
|
name = config.getName();
|
||||||
|
|
||||||
Path target = Paths.get(config.getOutputDir());
|
Path target = Paths.get(config.getOutputDir());
|
||||||
Path updated = rootDir.resolve(target);
|
Path updated = rootDir.resolve(target);
|
||||||
config.setOutputDir(updated.toString());
|
config.setOutputDir(updated.toString());
|
||||||
@ -308,34 +306,34 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
|
|||||||
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
|
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
|
||||||
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
|
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
|
||||||
TokenBuffer buffer = new TokenBuffer(p);
|
TokenBuffer buffer = new TokenBuffer(p);
|
||||||
|
|
||||||
recurse(buffer, p, codec, false);
|
recurse(buffer, p, codec, false);
|
||||||
|
|
||||||
JsonParser newParser = buffer.asParser(codec);
|
JsonParser newParser = buffer.asParser(codec);
|
||||||
newParser.nextToken();
|
newParser.nextToken();
|
||||||
|
|
||||||
return super.deserialize(newParser, ctx);
|
return super.deserialize(newParser, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
|
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
|
||||||
boolean firstToken = true;
|
boolean firstToken = true;
|
||||||
JsonToken token;
|
JsonToken token;
|
||||||
|
|
||||||
while ((token = p.nextToken()) != null) {
|
while ((token = p.nextToken()) != null) {
|
||||||
String name = p.currentName();
|
String name = p.currentName();
|
||||||
|
|
||||||
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
|
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
|
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (JsonToken.VALUE_NULL.equals(token)) {
|
if (JsonToken.VALUE_NULL.equals(token)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
|
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
|
||||||
p.nextToken();
|
p.nextToken();
|
||||||
String fileName = p.getText();
|
String fileName = p.getText();
|
||||||
@ -348,7 +346,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
|
|||||||
} else {
|
} else {
|
||||||
buffer.copyCurrentEvent(p);
|
buffer.copyCurrentEvent(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
firstToken = false;
|
firstToken = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,8 @@
|
|||||||
package org.openapitools.codegen.cmd;
|
package org.openapitools.codegen.cmd;
|
||||||
|
|
||||||
import com.google.common.base.Objects;
|
import com.google.common.base.Objects;
|
||||||
|
|
||||||
import io.airlift.airline.Command;
|
import io.airlift.airline.Command;
|
||||||
import io.airlift.airline.Option;
|
import io.airlift.airline.Option;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.openapitools.codegen.CodegenConfig;
|
import org.openapitools.codegen.CodegenConfig;
|
||||||
import org.openapitools.codegen.CodegenConfigLoader;
|
import org.openapitools.codegen.CodegenConfigLoader;
|
||||||
@ -20,18 +18,18 @@ import java.util.stream.Collectors;
|
|||||||
@Command(name = "list", description = "Lists the available generators")
|
@Command(name = "list", description = "Lists the available generators")
|
||||||
public class ListGenerators extends OpenApiGeneratorCommand {
|
public class ListGenerators extends OpenApiGeneratorCommand {
|
||||||
|
|
||||||
@Option(name = {"-s", "--short" }, description = "shortened output (suitable for scripting)")
|
@Option(name = {"-s", "--short"}, description = "shortened output (suitable for scripting)")
|
||||||
private Boolean shortened = false;
|
private Boolean shortened = false;
|
||||||
|
|
||||||
@Option(name = {"-d", "--docsite" }, description = "format for docusaurus site output", hidden = true)
|
@Option(name = {"-d", "--docsite"}, description = "format for docusaurus site output", hidden = true)
|
||||||
private Boolean docusaurus = false;
|
private Boolean docusaurus = false;
|
||||||
|
|
||||||
@Option(name = {"--github-nested-index" }, description = "format for github index at docs/generators/README.md", hidden = true)
|
@Option(name = {"--github-nested-index"}, description = "format for github index at docs/generators/README.md", hidden = true)
|
||||||
private Boolean githubNestedIndex = false;
|
private Boolean githubNestedIndex = false;
|
||||||
|
|
||||||
@Option(name = {"-i", "--include" },
|
@Option(name = {"-i", "--include"},
|
||||||
description = "comma-separated list of stability indexes to include (value: all,beta,stable,experimental,deprecated). Excludes deprecated by default.",
|
description = "comma-separated list of stability indexes to include (value: all,beta,stable,experimental,deprecated). Excludes deprecated by default.",
|
||||||
allowedValues = { "all", "beta", "stable", "experimental", "deprecated" })
|
allowedValues = {"all", "beta", "stable", "experimental", "deprecated"})
|
||||||
private String include = "stable,beta,experimental";
|
private String include = "stable,beta,experimental";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -88,7 +86,7 @@ public class ListGenerators extends OpenApiGeneratorCommand {
|
|||||||
.sorted(Comparator.comparing(CodegenConfig::getName))
|
.sorted(Comparator.comparing(CodegenConfig::getName))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
if(!list.isEmpty()) {
|
if (!list.isEmpty()) {
|
||||||
if (docusaurus || githubNestedIndex) {
|
if (docusaurus || githubNestedIndex) {
|
||||||
sb.append("## ").append(typeName).append(" generators");
|
sb.append("## ").append(typeName).append(" generators");
|
||||||
} else {
|
} else {
|
||||||
|
@ -17,9 +17,7 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen.cmd;
|
package org.openapitools.codegen.cmd;
|
||||||
|
|
||||||
import static ch.lambdaj.collection.LambdaCollections.with;
|
import ch.lambdaj.function.convert.Converter;
|
||||||
import static com.google.common.base.Joiner.on;
|
|
||||||
|
|
||||||
import com.google.common.base.CaseFormat;
|
import com.google.common.base.CaseFormat;
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
@ -31,9 +29,9 @@ import org.openapitools.codegen.CodegenConfig;
|
|||||||
import org.openapitools.codegen.SupportingFile;
|
import org.openapitools.codegen.SupportingFile;
|
||||||
import org.openapitools.codegen.TemplateManager;
|
import org.openapitools.codegen.TemplateManager;
|
||||||
import org.openapitools.codegen.api.TemplatePathLocator;
|
import org.openapitools.codegen.api.TemplatePathLocator;
|
||||||
|
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
|
||||||
import org.openapitools.codegen.templating.MustacheEngineAdapter;
|
import org.openapitools.codegen.templating.MustacheEngineAdapter;
|
||||||
import org.openapitools.codegen.templating.TemplateManagerOptions;
|
import org.openapitools.codegen.templating.TemplateManagerOptions;
|
||||||
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -43,7 +41,8 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import ch.lambdaj.function.convert.Converter;
|
import static ch.lambdaj.collection.LambdaCollections.with;
|
||||||
|
import static com.google.common.base.Joiner.on;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User: lanwen Date: 24.03.15 Time: 20:22
|
* User: lanwen Date: 24.03.15 Time: 20:22
|
||||||
@ -99,19 +98,19 @@ public class Meta extends OpenApiGeneratorCommand {
|
|||||||
new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
|
new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
|
||||||
new SupportingFile("kotlin/README.mustache", "", "README.md"),
|
new SupportingFile("kotlin/README.mustache", "", "README.md"),
|
||||||
|
|
||||||
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
|
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
|
||||||
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
|
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
|
||||||
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
|
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
|
||||||
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
|
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
|
||||||
: ImmutableList.of(
|
: ImmutableList.of(
|
||||||
new SupportingFile("pom.mustache", "", "pom.xml"),
|
new SupportingFile("pom.mustache", "", "pom.xml"),
|
||||||
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
|
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
|
||||||
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
|
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
|
||||||
new SupportingFile("README.mustache", "", "README.md"),
|
new SupportingFile("README.mustache", "", "README.md"),
|
||||||
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
|
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
|
||||||
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
|
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
|
||||||
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
|
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
|
||||||
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
|
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
|
||||||
|
|
||||||
String currentVersion = buildInfo.getVersion();
|
String currentVersion = buildInfo.getVersion();
|
||||||
|
|
||||||
@ -134,11 +133,11 @@ public class Meta extends OpenApiGeneratorCommand {
|
|||||||
* destination directory
|
* destination directory
|
||||||
*
|
*
|
||||||
* @param targetDir - destination directory
|
* @param targetDir - destination directory
|
||||||
* @param data - map with additional params needed to process templates
|
* @param data - map with additional params needed to process templates
|
||||||
* @return converter object to pass to lambdaj
|
* @return converter object to pass to lambdaj
|
||||||
*/
|
*/
|
||||||
private static Converter<SupportingFile, File> processFiles(final File targetDir,
|
private static Converter<SupportingFile, File> processFiles(final File targetDir,
|
||||||
final Map<String, Object> data) {
|
final Map<String, Object> data) {
|
||||||
return support -> {
|
return support -> {
|
||||||
try {
|
try {
|
||||||
File destinationFolder =
|
File destinationFolder =
|
||||||
@ -148,7 +147,7 @@ public class Meta extends OpenApiGeneratorCommand {
|
|||||||
TemplateManager templateProcessor = new TemplateManager(
|
TemplateManager templateProcessor = new TemplateManager(
|
||||||
new TemplateManagerOptions(false, false),
|
new TemplateManagerOptions(false, false),
|
||||||
new MustacheEngineAdapter(),
|
new MustacheEngineAdapter(),
|
||||||
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") }
|
new TemplatePathLocator[]{new CommonTemplateContentLocator("codegen")}
|
||||||
);
|
);
|
||||||
|
|
||||||
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());
|
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());
|
||||||
|
@ -19,7 +19,6 @@ package org.openapitools.codegen.cmd;
|
|||||||
|
|
||||||
import io.airlift.airline.Command;
|
import io.airlift.airline.Command;
|
||||||
import io.airlift.airline.Option;
|
import io.airlift.airline.Option;
|
||||||
|
|
||||||
import io.swagger.parser.OpenAPIParser;
|
import io.swagger.parser.OpenAPIParser;
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
||||||
@ -35,7 +34,7 @@ import java.util.HashSet;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@SuppressWarnings({"unused","java:S106"})
|
@SuppressWarnings({"unused", "java:S106"})
|
||||||
@Command(name = "validate", description = "Validate specification")
|
@Command(name = "validate", description = "Validate specification")
|
||||||
public class Validate extends OpenApiGeneratorCommand {
|
public class Validate extends OpenApiGeneratorCommand {
|
||||||
|
|
||||||
@ -43,7 +42,7 @@ public class Validate extends OpenApiGeneratorCommand {
|
|||||||
description = "location of the OpenAPI spec, as URL or file (required)")
|
description = "location of the OpenAPI spec, as URL or file (required)")
|
||||||
private String spec;
|
private String spec;
|
||||||
|
|
||||||
@Option(name = { "--recommend"}, title = "recommend spec improvements")
|
@Option(name = {"--recommend"}, title = "recommend spec improvements")
|
||||||
private Boolean recommend;
|
private Boolean recommend;
|
||||||
|
|
||||||
@Option(
|
@Option(
|
||||||
|
@ -20,7 +20,7 @@ public class AuthorTemplateTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void smokeTestAuthorTemplateCommand(){
|
public void smokeTestAuthorTemplateCommand() {
|
||||||
Cli.CliBuilder<Runnable> builder = createBuilder();
|
Cli.CliBuilder<Runnable> builder = createBuilder();
|
||||||
String[] arguments = new String[]{
|
String[] arguments = new String[]{
|
||||||
"author",
|
"author",
|
||||||
@ -57,7 +57,7 @@ public class AuthorTemplateTest {
|
|||||||
Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/auth/RetryingOAuth.mustache")));
|
Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/auth/RetryingOAuth.mustache")));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Cli.CliBuilder<Runnable> createBuilder(){
|
private Cli.CliBuilder<Runnable> createBuilder() {
|
||||||
Cli.CliBuilder<Runnable> builder = new Cli.CliBuilder<>("openapi-generator-cli");
|
Cli.CliBuilder<Runnable> builder = new Cli.CliBuilder<>("openapi-generator-cli");
|
||||||
|
|
||||||
builder.withGroup("author")
|
builder.withGroup("author")
|
||||||
|
@ -42,7 +42,7 @@ public class GenerateBatchTest {
|
|||||||
|
|
||||||
@DataProvider(name = "customIncludeDeserializerFiles")
|
@DataProvider(name = "customIncludeDeserializerFiles")
|
||||||
public Object[][] customIncludeDeserializerFiles() {
|
public Object[][] customIncludeDeserializerFiles() {
|
||||||
return new Object[][] {
|
return new Object[][]{
|
||||||
{JAXRS_DATELIB_J8_JSON},
|
{JAXRS_DATELIB_J8_JSON},
|
||||||
{JAXRS_DATELIB_J8_YAML},
|
{JAXRS_DATELIB_J8_YAML},
|
||||||
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
|
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
|
||||||
@ -89,7 +89,7 @@ public class GenerateBatchTest {
|
|||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
@Test(
|
@Test(
|
||||||
expectedExceptions = { RuntimeException.class },
|
expectedExceptions = {RuntimeException.class},
|
||||||
expectedExceptionsMessageRegExp = "Unable to deserialize config file: .*"
|
expectedExceptionsMessageRegExp = "Unable to deserialize config file: .*"
|
||||||
)
|
)
|
||||||
public void testInvalidDeserializerWithIncludeOption() {
|
public void testInvalidDeserializerWithIncludeOption() {
|
||||||
|
@ -363,7 +363,7 @@ public class GenerateTest {
|
|||||||
verify(configurator).toContext();
|
verify(configurator).toContext();
|
||||||
verifyNoMoreInteractions(configurator);
|
verifyNoMoreInteractions(configurator);
|
||||||
} finally {
|
} finally {
|
||||||
if(!f.delete()) {
|
if (!f.delete()) {
|
||||||
System.out.println("Directory didn't delete. You can ignore this.");
|
System.out.println("Directory didn't delete. You can ignore this.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -389,7 +389,7 @@ public class GenerateTest {
|
|||||||
verify(configurator).toClientOptInput();
|
verify(configurator).toClientOptInput();
|
||||||
verify(configurator).toContext();
|
verify(configurator).toContext();
|
||||||
verifyNoMoreInteractions(configurator);
|
verifyNoMoreInteractions(configurator);
|
||||||
if(!f.delete()) {
|
if (!f.delete()) {
|
||||||
System.out.println("Directory didn't delete. You can ignore this.");
|
System.out.println("Directory didn't delete. You can ignore this.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,8 +17,8 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen.cmd.utils;
|
package org.openapitools.codegen.cmd.utils;
|
||||||
|
|
||||||
import org.openapitools.codegen.utils.OptionUtils;
|
|
||||||
import org.apache.commons.lang3.tuple.Pair;
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
|
import org.openapitools.codegen.utils.OptionUtils;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
@ -27,7 +27,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
|
|||||||
* Gets all possible template paths for a given location.
|
* Gets all possible template paths for a given location.
|
||||||
*
|
*
|
||||||
* @param location The full location of the template.
|
* @param location The full location of the template.
|
||||||
*
|
|
||||||
* @return A new array of locations, modified according to the extensions or other adapter rules.
|
* @return A new array of locations, modified according to the extensions or other adapter rules.
|
||||||
*/
|
*/
|
||||||
protected String[] getModifiedFileLocation(String location) {
|
protected String[] getModifiedFileLocation(String location) {
|
||||||
@ -44,7 +43,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
|
|||||||
* Returns the path without an extension for an input location.
|
* Returns the path without an extension for an input location.
|
||||||
*
|
*
|
||||||
* @param location The location of the file, with original file extension intact.
|
* @param location The location of the file, with original file extension intact.
|
||||||
*
|
|
||||||
* @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
|
* @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
|
||||||
*/
|
*/
|
||||||
private String getPathWithoutExtension(String location) {
|
private String getPathWithoutExtension(String location) {
|
||||||
|
@ -17,7 +17,7 @@ public class TemplateDefinition {
|
|||||||
/**
|
/**
|
||||||
* <p>Constructor for TemplateDefinition.</p>
|
* <p>Constructor for TemplateDefinition.</p>
|
||||||
*
|
*
|
||||||
* @param templateFile a template path relative to user template or embedded template.
|
* @param templateFile a template path relative to user template or embedded template.
|
||||||
* @param destinationFilename a target output location for the file, relative to the output directory.
|
* @param destinationFilename a target output location for the file, relative to the output directory.
|
||||||
*/
|
*/
|
||||||
public TemplateDefinition(String templateFile, String destinationFilename) {
|
public TemplateDefinition(String templateFile, String destinationFilename) {
|
||||||
@ -34,8 +34,8 @@ public class TemplateDefinition {
|
|||||||
/**
|
/**
|
||||||
* <p>Constructor for TemplateDefinition.</p>
|
* <p>Constructor for TemplateDefinition.</p>
|
||||||
*
|
*
|
||||||
* @param templateFile a template path relative to user template or embedded template.
|
* @param templateFile a template path relative to user template or embedded template.
|
||||||
* @param folder a folder in the target output directory in which to place the target file.
|
* @param folder a folder in the target output directory in which to place the target file.
|
||||||
* @param destinationFilename a target output location for the file, relative to the output directory.
|
* @param destinationFilename a target output location for the file, relative to the output directory.
|
||||||
*/
|
*/
|
||||||
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
|
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
|
||||||
@ -94,7 +94,9 @@ public class TemplateDefinition {
|
|||||||
this.templateType = templateType;
|
this.templateType = templateType;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** {@inheritDoc} */
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
@ -106,13 +108,17 @@ public class TemplateDefinition {
|
|||||||
getTemplateType() == that.getTemplateType();
|
getTemplateType() == that.getTemplateType();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** {@inheritDoc} */
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
|
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** {@inheritDoc} */
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")
|
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")
|
||||||
|
@ -17,16 +17,22 @@ public enum TemplateFileType {
|
|||||||
|
|
||||||
private final String templateType;
|
private final String templateType;
|
||||||
|
|
||||||
TemplateFileType(String templateType) { this.templateType = templateType; }
|
TemplateFileType(String templateType) {
|
||||||
|
this.templateType = templateType;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the value for this template file type
|
* Returns the value for this template file type
|
||||||
*
|
*
|
||||||
* @return The template type of this enum.
|
* @return The template type of this enum.
|
||||||
*/
|
*/
|
||||||
public String value() { return this.templateType; }
|
public String value() {
|
||||||
|
return this.templateType;
|
||||||
|
}
|
||||||
|
|
||||||
/** {@inheritDoc} */
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")
|
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")
|
||||||
|
@ -12,10 +12,9 @@ public interface TemplateProcessor {
|
|||||||
/**
|
/**
|
||||||
* Writes data to a compiled template
|
* Writes data to a compiled template
|
||||||
*
|
*
|
||||||
* @param data Input data
|
* @param data Input data
|
||||||
* @param template Input template location
|
* @param template Input template location
|
||||||
* @param target The targeted file output location
|
* @param target The targeted file output location
|
||||||
*
|
|
||||||
* @return The actual file
|
* @return The actual file
|
||||||
* @throws IOException If file cannot be written.
|
* @throws IOException If file cannot be written.
|
||||||
*/
|
*/
|
||||||
@ -34,7 +33,7 @@ public interface TemplateProcessor {
|
|||||||
/**
|
/**
|
||||||
* Allow a caller to mark a path as ignored with accompanying reason
|
* Allow a caller to mark a path as ignored with accompanying reason
|
||||||
*
|
*
|
||||||
* @param path The ignored path
|
* @param path The ignored path
|
||||||
* @param context The reason for ignoring this path
|
* @param context The reason for ignoring this path
|
||||||
*/
|
*/
|
||||||
void ignore(Path path, String context);
|
void ignore(Path path, String context);
|
||||||
@ -42,7 +41,7 @@ public interface TemplateProcessor {
|
|||||||
/**
|
/**
|
||||||
* Allow a caller to mark a path as skipped with accompanying reason
|
* Allow a caller to mark a path as skipped with accompanying reason
|
||||||
*
|
*
|
||||||
* @param path The skipped path
|
* @param path The skipped path
|
||||||
* @param context The reason for skipping this path
|
* @param context The reason for skipping this path
|
||||||
*/
|
*/
|
||||||
void skip(Path path, String context);
|
void skip(Path path, String context);
|
||||||
@ -50,8 +49,9 @@ public interface TemplateProcessor {
|
|||||||
/**
|
/**
|
||||||
* Allow a caller to mark a path having errored during processing with accompanying reason
|
* Allow a caller to mark a path having errored during processing with accompanying reason
|
||||||
*
|
*
|
||||||
* @param path The path which has caused an error
|
* @param path The path which has caused an error
|
||||||
* @param context The reason for the error
|
* @param context The reason for the error
|
||||||
*/
|
*/
|
||||||
default void error(Path path, String context) { }
|
default void error(Path path, String context) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -47,8 +47,8 @@ public interface TemplatingEngineAdapter {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if the adapter handles compilation of the file
|
* Determine if the adapter handles compilation of the file
|
||||||
* @param filename The template filename
|
|
||||||
*
|
*
|
||||||
|
* @param filename The template filename
|
||||||
* @return True if the file should be compiled by this adapter, else false.
|
* @return True if the file should be compiled by this adapter, else false.
|
||||||
*/
|
*/
|
||||||
default boolean handlesFile(String filename) {
|
default boolean handlesFile(String filename) {
|
||||||
@ -58,7 +58,7 @@ public interface TemplatingEngineAdapter {
|
|||||||
/**
|
/**
|
||||||
* Compiles a template into a string
|
* Compiles a template into a string
|
||||||
*
|
*
|
||||||
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
|
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
|
||||||
* @param bundle The map of values to pass to the template
|
* @param bundle The map of values to pass to the template
|
||||||
* @param templateFile The name of the template (e.g. model.mustache )
|
* @param templateFile The name of the template (e.g. model.mustache )
|
||||||
* @return the processed template result
|
* @return the processed template result
|
||||||
|
@ -17,6 +17,7 @@
|
|||||||
package org.openapitools.codegen.api;
|
package org.openapitools.codegen.api;
|
||||||
|
|
||||||
// TODO: 6.0 Remove
|
// TODO: 6.0 Remove
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* interface to the full template content
|
* interface to the full template content
|
||||||
* implementers might take into account the -t cli option,
|
* implementers might take into account the -t cli option,
|
||||||
|
@ -340,7 +340,7 @@ public class WorkflowSettings {
|
|||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder withOutputDir(String outputDir) {
|
public Builder withOutputDir(String outputDir) {
|
||||||
if (outputDir != null ) {
|
if (outputDir != null) {
|
||||||
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
|
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
|
||||||
} else {
|
} else {
|
||||||
this.outputDir = DEFAULT_OUTPUT_DIR;
|
this.outputDir = DEFAULT_OUTPUT_DIR;
|
||||||
@ -473,7 +473,7 @@ public class WorkflowSettings {
|
|||||||
// check to see if the folder exists
|
// check to see if the folder exists
|
||||||
if (f.exists() && f.isDirectory()) {
|
if (f.exists() && f.isDirectory()) {
|
||||||
uri = f.toURI();
|
uri = f.toURI();
|
||||||
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
|
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
|
||||||
} else {
|
} else {
|
||||||
String cpDir;
|
String cpDir;
|
||||||
// HACK: this duplicates TemplateManager.getCPResourcePath a bit. We should probably move that function to core.
|
// HACK: this duplicates TemplateManager.getCPResourcePath a bit. We should probably move that function to core.
|
||||||
@ -543,7 +543,7 @@ public class WorkflowSettings {
|
|||||||
/**
|
/**
|
||||||
* Sets the {@code globalProperties} and returns a reference to this Builder so that the methods can be chained together.
|
* Sets the {@code globalProperties} and returns a reference to this Builder so that the methods can be chained together.
|
||||||
*
|
*
|
||||||
* @param key The key of a system (global) property to set
|
* @param key The key of a system (global) property to set
|
||||||
* @param value The value of a system (global) property to set
|
* @param value The value of a system (global) property to set
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
|
@ -383,7 +383,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link ClientModificationFeature} to the new/existing set of supported features.
|
* Includes the defined {@link ClientModificationFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are included in the set.
|
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
|
public Builder includeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
|
||||||
@ -395,7 +394,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link ClientModificationFeature} from the set of supported features.
|
* Excludes the defined {@link ClientModificationFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are excluded from the set.
|
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
|
public Builder excludeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
|
||||||
@ -422,7 +420,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link DataTypeFeature} to the new/existing set of supported features.
|
* Includes the defined {@link DataTypeFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are included in the set.
|
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
|
public Builder includeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
|
||||||
@ -434,7 +431,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link DataTypeFeature} from the set of supported features.
|
* Excludes the defined {@link DataTypeFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are excluded from the set.
|
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
|
public Builder excludeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
|
||||||
@ -461,7 +457,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link DocumentationFeature} to the new/existing set of supported features.
|
* Includes the defined {@link DocumentationFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param documentationFeature One or more {@code documentationFeature} to ensure are included in the set.
|
* @param documentationFeature One or more {@code documentationFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeDocumentationFeatures(DocumentationFeature... documentationFeature) {
|
public Builder includeDocumentationFeatures(DocumentationFeature... documentationFeature) {
|
||||||
@ -473,7 +468,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link DocumentationFeature} from the set of supported features.
|
* Excludes the defined {@link DocumentationFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param documentationFeature One or more {@code documentationFeature} to ensure are excluded from the set.
|
* @param documentationFeature One or more {@code documentationFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeDocumentationFeatures(DocumentationFeature... documentationFeature) {
|
public Builder excludeDocumentationFeatures(DocumentationFeature... documentationFeature) {
|
||||||
@ -500,7 +494,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link SchemaSupportFeature} to the new/existing set of supported features.
|
* Includes the defined {@link SchemaSupportFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are included in the set.
|
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
|
public Builder includeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
|
||||||
@ -512,7 +505,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link SchemaSupportFeature} from the set of supported features.
|
* Excludes the defined {@link SchemaSupportFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are excluded from the set.
|
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
|
public Builder excludeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
|
||||||
@ -539,7 +531,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link ParameterFeature} to the new/existing set of supported features.
|
* Includes the defined {@link ParameterFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param parameterFeature One or more {@code parameterFeature} to ensure are included in the set.
|
* @param parameterFeature One or more {@code parameterFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeParameterFeatures(ParameterFeature... parameterFeature) {
|
public Builder includeParameterFeatures(ParameterFeature... parameterFeature) {
|
||||||
@ -551,7 +542,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link ParameterFeature} from the set of supported features.
|
* Excludes the defined {@link ParameterFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param parameterFeature One or more {@code parameterFeature} to ensure are excluded from the set.
|
* @param parameterFeature One or more {@code parameterFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeParameterFeatures(ParameterFeature... parameterFeature) {
|
public Builder excludeParameterFeatures(ParameterFeature... parameterFeature) {
|
||||||
@ -578,7 +568,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link SecurityFeature} to the new/existing set of supported features.
|
* Includes the defined {@link SecurityFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param securityFeature One or more {@code securityFeature} to ensure are included in the set.
|
* @param securityFeature One or more {@code securityFeature} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeSecurityFeatures(SecurityFeature... securityFeature) {
|
public Builder includeSecurityFeatures(SecurityFeature... securityFeature) {
|
||||||
@ -590,7 +579,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link SecurityFeature} from the set of supported features.
|
* Excludes the defined {@link SecurityFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param securityFeature One or more {@code securityFeature} to ensure are excluded from the set.
|
* @param securityFeature One or more {@code securityFeature} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeSecurityFeatures(SecurityFeature... securityFeature) {
|
public Builder excludeSecurityFeatures(SecurityFeature... securityFeature) {
|
||||||
@ -617,7 +605,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link GlobalFeature} to the new/existing set of supported features.
|
* Includes the defined {@link GlobalFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param globalFeature One or more {@code globalFeatures} to ensure are included in the set.
|
* @param globalFeature One or more {@code globalFeatures} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeGlobalFeatures(GlobalFeature... globalFeature) {
|
public Builder includeGlobalFeatures(GlobalFeature... globalFeature) {
|
||||||
@ -629,7 +616,6 @@ public class FeatureSet {
|
|||||||
* Excludes the defined {@link GlobalFeature} from the set of supported features.
|
* Excludes the defined {@link GlobalFeature} from the set of supported features.
|
||||||
*
|
*
|
||||||
* @param globalFeature One or more {@code globalFeatures} to ensure are excluded from the set.
|
* @param globalFeature One or more {@code globalFeatures} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeGlobalFeatures(GlobalFeature... globalFeature) {
|
public Builder excludeGlobalFeatures(GlobalFeature... globalFeature) {
|
||||||
@ -656,7 +642,6 @@ public class FeatureSet {
|
|||||||
* Includes the defined {@link WireFormatFeature} to the new/existing set of supported features.
|
* Includes the defined {@link WireFormatFeature} to the new/existing set of supported features.
|
||||||
*
|
*
|
||||||
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are included in the set.
|
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are included in the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder includeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
|
public Builder includeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
|
||||||
@ -672,7 +657,6 @@ public class FeatureSet {
|
|||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are excluded from the set.
|
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are excluded from the set.
|
||||||
*
|
|
||||||
* @return a reference to this Builder
|
* @return a reference to this Builder
|
||||||
*/
|
*/
|
||||||
public Builder excludeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
|
public Builder excludeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
|
||||||
|
@ -49,10 +49,12 @@ public enum Stability {
|
|||||||
*
|
*
|
||||||
* @return The descriptive value of this enum.
|
* @return The descriptive value of this enum.
|
||||||
*/
|
*/
|
||||||
public String value() { return description; }
|
public String value() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
public static Stability forDescription(String description) {
|
public static Stability forDescription(String description) {
|
||||||
for (Stability value: values()) {
|
for (Stability value : values()) {
|
||||||
if (value.description.equals(description)) {
|
if (value.description.equals(description)) {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@ import org.openapitools.codegen.meta.features.annotations.ToolingExtension;
|
|||||||
/**
|
/**
|
||||||
* Defines common data types supported by a generator.
|
* Defines common data types supported by a generator.
|
||||||
* Some of these features are defined in specs, and some are specific to the tool.
|
* Some of these features are defined in specs, and some are specific to the tool.
|
||||||
*
|
* <p>
|
||||||
* Where data types are listed as tool-specific, this either indicates that the data type is common enough that it is an officially
|
* Where data types are listed as tool-specific, this either indicates that the data type is common enough that it is an officially
|
||||||
* supported custom data type by the toolset (see {@link DataTypeFeature#Decimal}), or that the consideration of a special type isn't
|
* supported custom data type by the toolset (see {@link DataTypeFeature#Decimal}), or that the consideration of a special type isn't
|
||||||
* explicitly mentioned by the specification(s) but differs enough across languages that it warrants a special callout (see {@link DataTypeFeature#ArrayOfModel}).
|
* explicitly mentioned by the specification(s) but differs enough across languages that it warrants a special callout (see {@link DataTypeFeature#ArrayOfModel}).
|
||||||
@ -114,9 +114,9 @@ public enum DataTypeFeature {
|
|||||||
*
|
*
|
||||||
*
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* This should be used as an indicator for password best practices, such as assigning a variable to
|
* This should be used as an indicator for password best practices, such as assigning a variable to
|
||||||
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
|
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
|
||||||
* in any user inputs. See OWASP for best practices.
|
* in any user inputs. See OWASP for best practices.
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
@OAS2 @OAS3
|
@OAS2 @OAS3
|
||||||
|
@ -129,7 +129,7 @@ public enum GlobalFeature {
|
|||||||
*
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* NOTE: This option is more relevant for documentation generators which support HTML stylesheets, but may be used
|
* NOTE: This option is more relevant for documentation generators which support HTML stylesheets, but may be used
|
||||||
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
|
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
@OAS3
|
@OAS3
|
||||||
|
@ -45,7 +45,7 @@ public enum ParameterFeature {
|
|||||||
* Supports body parameters.
|
* Supports body parameters.
|
||||||
*
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
|
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
@OAS2
|
@OAS2
|
||||||
@ -53,7 +53,7 @@ public enum ParameterFeature {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Supports form encoded parameters.
|
* Supports form encoded parameters.
|
||||||
*
|
* <p>
|
||||||
* OAS 3.x specification supports this structurally via content types rather than as an "in" parameter.
|
* OAS 3.x specification supports this structurally via content types rather than as an "in" parameter.
|
||||||
*/
|
*/
|
||||||
@OAS2
|
@OAS2
|
||||||
|
@ -54,11 +54,11 @@ public enum SchemaSupportFeature {
|
|||||||
*
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* This means that a single "Type" in generated code may refer to one of any type in a set of 2 or more types.
|
* This means that a single "Type" in generated code may refer to one of any type in a set of 2 or more types.
|
||||||
*
|
* <p>
|
||||||
* This is defined as a union as "OneOf" support is not explicitly limited to physical boundaries in OpenAPI Specification. The
|
* This is defined as a union as "OneOf" support is not explicitly limited to physical boundaries in OpenAPI Specification. The
|
||||||
* implementation of such a type is easily represented dynamically (a JSON object), but requires explicit language support and
|
* implementation of such a type is easily represented dynamically (a JSON object), but requires explicit language support and
|
||||||
* potentially a custom implementation (typed instances).
|
* potentially a custom implementation (typed instances).
|
||||||
*
|
* <p>
|
||||||
* Note that a generator may support "Unions" very loosely by returning an Object/Any/ref/interface{} type, leaving onus
|
* Note that a generator may support "Unions" very loosely by returning an Object/Any/ref/interface{} type, leaving onus
|
||||||
* on type determination to the consumer. This does *NOT* suggest generated code implements a "Union Type".
|
* on type determination to the consumer. This does *NOT* suggest generated code implements a "Union Type".
|
||||||
* </p>
|
* </p>
|
||||||
|
@ -4,9 +4,9 @@ public enum AnnotationType {
|
|||||||
OAS2, OAS3, ToolingExtension;
|
OAS2, OAS3, ToolingExtension;
|
||||||
|
|
||||||
public static AnnotationType fromAnnotation(Class<?> input) {
|
public static AnnotationType fromAnnotation(Class<?> input) {
|
||||||
if(input == OAS2.class) return AnnotationType.OAS2;
|
if (input == OAS2.class) return AnnotationType.OAS2;
|
||||||
if(input == OAS3.class) return AnnotationType.OAS3;
|
if (input == OAS3.class) return AnnotationType.OAS3;
|
||||||
if(input == ToolingExtension.class) return AnnotationType.ToolingExtension;
|
if (input == ToolingExtension.class) return AnnotationType.ToolingExtension;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,6 @@ public class GenericValidator<TInput> implements Validator<TInput> {
|
|||||||
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
|
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
|
||||||
*
|
*
|
||||||
* @param input The object instance to be validated.
|
* @param input The object instance to be validated.
|
||||||
*
|
|
||||||
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
|
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
|
@ -28,7 +28,7 @@ public final class Invalid extends Validated {
|
|||||||
/**
|
/**
|
||||||
* Constructs a new {@link Invalid} instance.
|
* Constructs a new {@link Invalid} instance.
|
||||||
*
|
*
|
||||||
* @param rule The rule which was evaluated and resulted in this state.
|
* @param rule The rule which was evaluated and resulted in this state.
|
||||||
* @param message The message to be displayed for this invalid state.
|
* @param message The message to be displayed for this invalid state.
|
||||||
*/
|
*/
|
||||||
Invalid(ValidationRule rule, String message) {
|
Invalid(ValidationRule rule, String message) {
|
||||||
@ -39,7 +39,7 @@ public final class Invalid extends Validated {
|
|||||||
/**
|
/**
|
||||||
* Constructs a new {@link Invalid} instance.
|
* Constructs a new {@link Invalid} instance.
|
||||||
*
|
*
|
||||||
* @param rule The rule which was evaluated and resulted in this state.
|
* @param rule The rule which was evaluated and resulted in this state.
|
||||||
* @param message The message to be displayed for this invalid state.
|
* @param message The message to be displayed for this invalid state.
|
||||||
* @param details Additional contextual details related to the invalid state.
|
* @param details Additional contextual details related to the invalid state.
|
||||||
*/
|
*/
|
||||||
|
@ -46,21 +46,20 @@ public abstract class Validated {
|
|||||||
/**
|
/**
|
||||||
* Creates an instance of an {@link Invalid} validation state.
|
* Creates an instance of an {@link Invalid} validation state.
|
||||||
*
|
*
|
||||||
* @param rule The rule which was evaluated.
|
* @param rule The rule which was evaluated.
|
||||||
* @param message The message to display to a user.
|
* @param message The message to display to a user.
|
||||||
*
|
|
||||||
* @return A {@link Validated} instance representing an invalid state according to the rule.
|
* @return A {@link Validated} instance representing an invalid state according to the rule.
|
||||||
*/
|
*/
|
||||||
public static Validated invalid(ValidationRule rule, String message) {
|
public static Validated invalid(ValidationRule rule, String message) {
|
||||||
return new Invalid(rule, message);
|
return new Invalid(rule, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates an instance of an {@link Invalid} validation state.
|
* Creates an instance of an {@link Invalid} validation state.
|
||||||
*
|
*
|
||||||
* @param rule The rule which was evaluated.
|
* @param rule The rule which was evaluated.
|
||||||
* @param message The message to display to a user.
|
* @param message The message to display to a user.
|
||||||
* @param details Additional contextual details related to the invalid state.
|
* @param details Additional contextual details related to the invalid state.
|
||||||
*
|
|
||||||
* @return A {@link Validated} instance representing an invalid state according to the rule.
|
* @return A {@link Validated} instance representing an invalid state according to the rule.
|
||||||
*/
|
*/
|
||||||
public static Validated invalid(ValidationRule rule, String message, String details) {
|
public static Validated invalid(ValidationRule rule, String message, String details) {
|
||||||
@ -71,7 +70,6 @@ public abstract class Validated {
|
|||||||
* Creates an instance of an {@link Valid} validation state.
|
* Creates an instance of an {@link Valid} validation state.
|
||||||
*
|
*
|
||||||
* @param rule The rule which was evaluated.
|
* @param rule The rule which was evaluated.
|
||||||
*
|
|
||||||
* @return A {@link Validated} instance representing a valid state according to the rule.
|
* @return A {@link Validated} instance representing a valid state according to the rule.
|
||||||
*/
|
*/
|
||||||
public static Validated valid(ValidationRule rule) {
|
public static Validated valid(ValidationRule rule) {
|
||||||
|
@ -49,7 +49,7 @@ public final class ValidationResult {
|
|||||||
* @return All validated results.
|
* @return All validated results.
|
||||||
*/
|
*/
|
||||||
public List<Validated> getAll() {
|
public List<Validated> getAll() {
|
||||||
return validations;
|
return validations;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -57,8 +57,8 @@ public final class ValidationResult {
|
|||||||
*
|
*
|
||||||
* @return A list containing only {@link Valid} states.
|
* @return A list containing only {@link Valid} states.
|
||||||
*/
|
*/
|
||||||
public List<Valid> getValid(){
|
public List<Valid> getValid() {
|
||||||
return validations.stream().filter(Validated::isValid).map(it -> (Valid)it).collect(Collectors.toList());
|
return validations.stream().filter(Validated::isValid).map(it -> (Valid) it).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -66,10 +66,10 @@ public final class ValidationResult {
|
|||||||
*
|
*
|
||||||
* @return A list of all validation errors.
|
* @return A list of all validation errors.
|
||||||
*/
|
*/
|
||||||
public List<Invalid> getErrors(){
|
public List<Invalid> getErrors() {
|
||||||
return validations.stream()
|
return validations.stream()
|
||||||
.filter(it -> !it.isValid())
|
.filter(it -> !it.isValid())
|
||||||
.map(it -> (Invalid)it)
|
.map(it -> (Invalid) it)
|
||||||
.filter(it -> it.getSeverity().equals(Severity.ERROR))
|
.filter(it -> it.getSeverity().equals(Severity.ERROR))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
@ -79,10 +79,10 @@ public final class ValidationResult {
|
|||||||
*
|
*
|
||||||
* @return A list of all validation warnings.
|
* @return A list of all validation warnings.
|
||||||
*/
|
*/
|
||||||
public List<Invalid> getWarnings(){
|
public List<Invalid> getWarnings() {
|
||||||
return validations.stream()
|
return validations.stream()
|
||||||
.filter(it -> !it.isValid())
|
.filter(it -> !it.isValid())
|
||||||
.map(it -> (Invalid)it)
|
.map(it -> (Invalid) it)
|
||||||
.filter(it -> it.getSeverity().equals(Severity.WARNING))
|
.filter(it -> it.getSeverity().equals(Severity.WARNING))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
@ -31,11 +31,11 @@ public class ValidationRule {
|
|||||||
/**
|
/**
|
||||||
* Constructs a new instance of {@link ValidationRule}
|
* Constructs a new instance of {@link ValidationRule}
|
||||||
*
|
*
|
||||||
* @param severity The declared severity if this validation rule fails.
|
* @param severity The declared severity if this validation rule fails.
|
||||||
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
||||||
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
||||||
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
||||||
* the evaluated instance will be considered "valid" according to this rule.
|
* the evaluated instance will be considered "valid" according to this rule.
|
||||||
*/
|
*/
|
||||||
ValidationRule(Severity severity, String description, String failureMessage, Function<Object, Result> test) {
|
ValidationRule(Severity severity, String description, String failureMessage, Function<Object, Result> test) {
|
||||||
this.severity = severity;
|
this.severity = severity;
|
||||||
@ -57,7 +57,6 @@ public class ValidationRule {
|
|||||||
* Evaluate an instance of an object against this rule.
|
* Evaluate an instance of an object against this rule.
|
||||||
*
|
*
|
||||||
* @param input The instance to be evaluated.
|
* @param input The instance to be evaluated.
|
||||||
*
|
|
||||||
* @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
|
* @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
|
||||||
*/
|
*/
|
||||||
public Result evaluate(Object input) {
|
public Result evaluate(Object input) {
|
||||||
@ -90,19 +89,18 @@ public class ValidationRule {
|
|||||||
* @return An "empty" rule.
|
* @return An "empty" rule.
|
||||||
*/
|
*/
|
||||||
static ValidationRule empty() {
|
static ValidationRule empty() {
|
||||||
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty() );
|
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an instance of a {@link ValidationRule}
|
* Create an instance of a {@link ValidationRule}
|
||||||
*
|
*
|
||||||
* @param severity The declared severity if this validation rule fails.
|
* @param severity The declared severity if this validation rule fails.
|
||||||
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
||||||
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
||||||
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
||||||
* the evaluated instance will be considered "valid" according to this rule.
|
* the evaluated instance will be considered "valid" according to this rule.
|
||||||
* @param <T> The type of the object being evaluated.
|
* @param <T> The type of the object being evaluated.
|
||||||
*
|
|
||||||
* @return A new instance of a {@link ValidationRule}
|
* @return A new instance of a {@link ValidationRule}
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@ -114,10 +112,9 @@ public class ValidationRule {
|
|||||||
* Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail.
|
* Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail.
|
||||||
*
|
*
|
||||||
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
||||||
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
||||||
* the evaluated instance will be considered "valid" according to this rule.
|
* the evaluated instance will be considered "valid" according to this rule.
|
||||||
* @param <T> The type of the object being evaluated.
|
* @param <T> The type of the object being evaluated.
|
||||||
*
|
|
||||||
* @return A new instance of a {@link ValidationRule}
|
* @return A new instance of a {@link ValidationRule}
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@ -128,12 +125,11 @@ public class ValidationRule {
|
|||||||
/**
|
/**
|
||||||
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
|
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
|
||||||
*
|
*
|
||||||
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
|
||||||
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
|
||||||
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
|
||||||
* the evaluated instance will be considered "valid" according to this rule.
|
* the evaluated instance will be considered "valid" according to this rule.
|
||||||
* @param <T> The type of the object being evaluated.
|
* @param <T> The type of the object being evaluated.
|
||||||
*
|
|
||||||
* @return A new instance of a {@link ValidationRule}
|
* @return A new instance of a {@link ValidationRule}
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@ -164,17 +160,24 @@ public class ValidationRule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public abstract boolean passed();
|
public abstract boolean passed();
|
||||||
public final boolean failed() { return !passed(); }
|
|
||||||
|
public final boolean failed() {
|
||||||
|
return !passed();
|
||||||
|
}
|
||||||
|
|
||||||
public Throwable getThrowable() {
|
public Throwable getThrowable() {
|
||||||
return throwable;
|
return throwable;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean thrown() { return this.throwable == null; }
|
public boolean thrown() {
|
||||||
|
return this.throwable == null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class Pass extends Result {
|
public static final class Pass extends Result {
|
||||||
public static Result empty() { return new Pass(); }
|
public static Result empty() {
|
||||||
|
return new Pass();
|
||||||
|
}
|
||||||
|
|
||||||
public Pass() {
|
public Pass() {
|
||||||
super();
|
super();
|
||||||
@ -192,7 +195,9 @@ public class ValidationRule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static final class Fail extends Result {
|
public static final class Fail extends Result {
|
||||||
public static Result empty() { return new Fail(); }
|
public static Result empty() {
|
||||||
|
return new Fail();
|
||||||
|
}
|
||||||
|
|
||||||
public Fail() {
|
public Fail() {
|
||||||
super();
|
super();
|
||||||
|
@ -27,7 +27,6 @@ public interface Validator<TInput> {
|
|||||||
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
|
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
|
||||||
*
|
*
|
||||||
* @param input The object instance to be validated.
|
* @param input The object instance to be validated.
|
||||||
*
|
|
||||||
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
|
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
|
||||||
*/
|
*/
|
||||||
ValidationResult validate(TInput input);
|
ValidationResult validate(TInput input);
|
||||||
|
@ -25,7 +25,7 @@ import static org.testng.Assert.*;
|
|||||||
|
|
||||||
public class WorkflowSettingsTest {
|
public class WorkflowSettingsTest {
|
||||||
@Test
|
@Test
|
||||||
public void defaultValuesNotOverriddenByNulls(){
|
public void defaultValuesNotOverriddenByNulls() {
|
||||||
WorkflowSettings settings = WorkflowSettings.newBuilder()
|
WorkflowSettings settings = WorkflowSettings.newBuilder()
|
||||||
.withOutputDir(null)
|
.withOutputDir(null)
|
||||||
.withVerbose(null)
|
.withVerbose(null)
|
||||||
@ -50,7 +50,7 @@ public class WorkflowSettingsTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void newBuilderFromCopyShouldMutateGlobalProperties(){
|
public void newBuilderFromCopyShouldMutateGlobalProperties() {
|
||||||
WorkflowSettings original = WorkflowSettings.newBuilder()
|
WorkflowSettings original = WorkflowSettings.newBuilder()
|
||||||
.withOutputDir("output")
|
.withOutputDir("output")
|
||||||
.withVerbose(true)
|
.withVerbose(true)
|
||||||
@ -110,16 +110,17 @@ public class WorkflowSettingsTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void defaultValuesCanBeChangedClassConstructor(){
|
public void defaultValuesCanBeChangedClassConstructor() {
|
||||||
WorkflowSettings defaults = new WorkflowSettings();
|
WorkflowSettings defaults = new WorkflowSettings();
|
||||||
assertOnChangesToDefaults(defaults);
|
assertOnChangesToDefaults(defaults);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void defaultValuesCanBeChangedBuilder(){
|
public void defaultValuesCanBeChangedBuilder() {
|
||||||
WorkflowSettings defaults = WorkflowSettings.newBuilder().build();
|
WorkflowSettings defaults = WorkflowSettings.newBuilder().build();
|
||||||
assertOnChangesToDefaults(defaults);
|
assertOnChangesToDefaults(defaults);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void customOutputDirIsSet() {
|
public void customOutputDirIsSet() {
|
||||||
WorkflowSettings settings = WorkflowSettings.newBuilder()
|
WorkflowSettings settings = WorkflowSettings.newBuilder()
|
||||||
|
@ -18,12 +18,13 @@ package org.openapitools.codegen.validation;
|
|||||||
|
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
import static org.testng.Assert.*;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.testng.Assert.assertEquals;
|
||||||
|
import static org.testng.Assert.assertTrue;
|
||||||
|
|
||||||
public class GenericValidatorTest {
|
public class GenericValidatorTest {
|
||||||
static class Person {
|
static class Person {
|
||||||
private int age;
|
private int age;
|
||||||
@ -53,7 +54,7 @@ public class GenericValidatorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static ValidationRule.Result checkNameNormalLength(Person person) {
|
private static ValidationRule.Result checkNameNormalLength(Person person) {
|
||||||
return person.name.length() < 10? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
|
return person.name.length() < 10 ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ValidationRule> validationRules = Arrays.asList(
|
private List<ValidationRule> validationRules = Arrays.asList(
|
||||||
@ -65,7 +66,7 @@ public class GenericValidatorTest {
|
|||||||
);
|
);
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenericValidatorSuccesses(){
|
public void testGenericValidatorSuccesses() {
|
||||||
Person person = new Person("Jim", 23);
|
Person person = new Person("Jim", 23);
|
||||||
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
||||||
ValidationResult result = validator.validate(person);
|
ValidationResult result = validator.validate(person);
|
||||||
@ -79,7 +80,7 @@ public class GenericValidatorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenericValidatorSingleConditionFails(){
|
public void testGenericValidatorSingleConditionFails() {
|
||||||
Person person = new Person("Jim", 3);
|
Person person = new Person("Jim", 3);
|
||||||
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
||||||
ValidationResult result = validator.validate(person);
|
ValidationResult result = validator.validate(person);
|
||||||
@ -98,7 +99,7 @@ public class GenericValidatorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenericValidatorMultipleConditionsFail(){
|
public void testGenericValidatorMultipleConditionsFail() {
|
||||||
Person person = new Person("asdf", 3);
|
Person person = new Person("asdf", 3);
|
||||||
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
||||||
ValidationResult result = validator.validate(person);
|
ValidationResult result = validator.validate(person);
|
||||||
@ -122,7 +123,7 @@ public class GenericValidatorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenericValidatorErrorsAndWarnings(){
|
public void testGenericValidatorErrorsAndWarnings() {
|
||||||
Person person = new Person("0123456789asdfghjkl", 3);
|
Person person = new Person("0123456789asdfghjkl", 3);
|
||||||
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
|
||||||
ValidationResult result = validator.validate(person);
|
ValidationResult result = validator.validate(person);
|
||||||
|
@ -18,17 +18,18 @@ package org.openapitools.codegen.validation;
|
|||||||
|
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
import static org.testng.Assert.*;
|
import static org.testng.Assert.assertFalse;
|
||||||
|
import static org.testng.Assert.assertTrue;
|
||||||
|
|
||||||
public class ValidatedTest {
|
public class ValidatedTest {
|
||||||
@Test
|
@Test
|
||||||
public void isValidTrueForValidType(){
|
public void isValidTrueForValidType() {
|
||||||
boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
|
boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
|
||||||
assertTrue(isValid);
|
assertTrue(isValid);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void isValidFalseForInvalidType(){
|
public void isValidFalseForInvalidType() {
|
||||||
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
|
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
|
||||||
assertFalse(isValid);
|
assertFalse(isValid);
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,8 @@ package org.openapitools.codegen.validation;
|
|||||||
|
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
import static org.testng.Assert.*;
|
import static org.testng.Assert.assertFalse;
|
||||||
|
import static org.testng.Assert.assertTrue;
|
||||||
|
|
||||||
public class ValidationRuleTest {
|
public class ValidationRuleTest {
|
||||||
static class Sample {
|
static class Sample {
|
||||||
@ -39,11 +40,11 @@ public class ValidationRuleTest {
|
|||||||
|
|
||||||
private static ValidationRule.Result checkPattern(Sample input) {
|
private static ValidationRule.Result checkPattern(Sample input) {
|
||||||
String pattern = "^[A-Z][a-z]*$";
|
String pattern = "^[A-Z][a-z]*$";
|
||||||
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
|
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createMethodUsingMethodReference(){
|
public void createMethodUsingMethodReference() {
|
||||||
Sample nil = new Sample(null);
|
Sample nil = new Sample(null);
|
||||||
Sample six = new Sample("123456");
|
Sample six = new Sample("123456");
|
||||||
Sample seven = new Sample("1234567");
|
Sample seven = new Sample("1234567");
|
||||||
@ -56,11 +57,11 @@ public class ValidationRuleTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createMethodUsingLambda(){
|
public void createMethodUsingLambda() {
|
||||||
Sample nil = new Sample(null);
|
Sample nil = new Sample(null);
|
||||||
Sample lowercase = new Sample("jim");
|
Sample lowercase = new Sample("jim");
|
||||||
Sample titlecase = new Sample("Jim");
|
Sample titlecase = new Sample("Jim");
|
||||||
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample)i));
|
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample) i));
|
||||||
assertFalse(result.evaluate(nil).passed());
|
assertFalse(result.evaluate(nil).passed());
|
||||||
assertFalse(result.evaluate(lowercase).passed());
|
assertFalse(result.evaluate(lowercase).passed());
|
||||||
assertTrue(result.evaluate(titlecase).passed());
|
assertTrue(result.evaluate(titlecase).passed());
|
||||||
|
@ -30,11 +30,13 @@ import lombok.Setter;
|
|||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.maven.artifact.Artifact;
|
|
||||||
import org.apache.maven.plugin.AbstractMojo;
|
import org.apache.maven.plugin.AbstractMojo;
|
||||||
import org.apache.maven.plugin.MojoExecution;
|
import org.apache.maven.plugin.MojoExecution;
|
||||||
import org.apache.maven.plugin.MojoExecutionException;
|
import org.apache.maven.plugin.MojoExecutionException;
|
||||||
import org.apache.maven.plugins.annotations.*;
|
import org.apache.maven.plugins.annotations.Component;
|
||||||
|
import org.apache.maven.plugins.annotations.LifecyclePhase;
|
||||||
|
import org.apache.maven.plugins.annotations.Mojo;
|
||||||
|
import org.apache.maven.plugins.annotations.Parameter;
|
||||||
import org.apache.maven.project.MavenProject;
|
import org.apache.maven.project.MavenProject;
|
||||||
import org.apache.maven.project.MavenProjectHelper;
|
import org.apache.maven.project.MavenProjectHelper;
|
||||||
import org.openapitools.codegen.*;
|
import org.openapitools.codegen.*;
|
||||||
@ -49,7 +51,10 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.*;
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.text.MessageFormat;
|
import java.text.MessageFormat;
|
||||||
@ -156,7 +161,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
/**
|
/**
|
||||||
* The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
|
* The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
|
||||||
*/
|
*/
|
||||||
@Parameter(name = "engine", defaultValue = "mustache", property="openapi.generator.maven.plugin.engine")
|
@Parameter(name = "engine", defaultValue = "mustache", property = "openapi.generator.maven.plugin.engine")
|
||||||
private String engine;
|
private String engine;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -541,7 +546,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
|
|
||||||
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
|
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
|
||||||
inputSpec = new MergedSpecBuilder(inputSpecRootDirectory, mergedFileName)
|
inputSpec = new MergedSpecBuilder(inputSpecRootDirectory, mergedFileName)
|
||||||
.buildMergedSpec();
|
.buildMergedSpec();
|
||||||
LOGGER.info("Merge input spec would be used - {}", inputSpec);
|
LOGGER.info("Merge input spec would be used - {}", inputSpec);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -572,7 +577,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buildContext != null && inputSpec != null ) {
|
if (buildContext != null && inputSpec != null) {
|
||||||
if (buildContext.isIncremental() &&
|
if (buildContext.isIncremental() &&
|
||||||
inputSpecFile.exists() &&
|
inputSpecFile.exists() &&
|
||||||
!buildContext.hasDelta(inputSpecFile)) {
|
!buildContext.hasDelta(inputSpecFile)) {
|
||||||
@ -664,7 +669,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
configurator.setEnablePostProcessFile(enablePostProcessFile);
|
configurator.setEnablePostProcessFile(enablePostProcessFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (generateAliasAsModel != null) {
|
if (generateAliasAsModel != null) {
|
||||||
configurator.setGenerateAliasAsModel(generateAliasAsModel);
|
configurator.setGenerateAliasAsModel(generateAliasAsModel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -974,7 +979,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
File parent = new File(storedInputSpecHashFile.getParent());
|
File parent = new File(storedInputSpecHashFile.getParent());
|
||||||
if (!parent.mkdirs()) {
|
if (!parent.mkdirs()) {
|
||||||
throw new RuntimeException("Failed to create the folder " + parent.getAbsolutePath() +
|
throw new RuntimeException("Failed to create the folder " + parent.getAbsolutePath() +
|
||||||
" to store the checksum of the input spec.");
|
" to store the checksum of the input spec.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -993,7 +998,7 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculate an SHA256 hash for the openapi specification.
|
* Calculate an SHA256 hash for the openapi specification.
|
||||||
* If the specification is hosted on a remote resource it is downloaded first.
|
* If the specification is hosted on a remote resource it is downloaded first.
|
||||||
*
|
*
|
||||||
* @param inputSpec - Openapi specification input file. Can denote a URL or file path.
|
* @param inputSpec - Openapi specification input file. Can denote a URL or file path.
|
||||||
@ -1002,18 +1007,19 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
private String calculateInputSpecHash(String inputSpec) {
|
private String calculateInputSpecHash(String inputSpec) {
|
||||||
final ParseOptions parseOptions = new ParseOptions();
|
final ParseOptions parseOptions = new ParseOptions();
|
||||||
parseOptions.setResolve(true);
|
parseOptions.setResolve(true);
|
||||||
|
|
||||||
final URL remoteUrl = inputSpecRemoteUrl();
|
final URL remoteUrl = inputSpecRemoteUrl();
|
||||||
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
|
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
|
||||||
|
|
||||||
return Hashing.sha256().hashBytes(
|
return Hashing.sha256().hashBytes(
|
||||||
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), authorizationValues, parseOptions)
|
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), authorizationValues, parseOptions)
|
||||||
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
|
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
|
||||||
).toString();
|
).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Try to parse inputSpec setting string into URL
|
* Try to parse inputSpec setting string into URL
|
||||||
|
*
|
||||||
* @return A valid URL or null if inputSpec is not a valid URL
|
* @return A valid URL or null if inputSpec is not a valid URL
|
||||||
*/
|
*/
|
||||||
private URL inputSpecRemoteUrl() {
|
private URL inputSpecRemoteUrl() {
|
||||||
@ -1026,8 +1032,9 @@ public class CodeGenMojo extends AbstractMojo {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get specification hash file
|
* Get specification hash file
|
||||||
|
*
|
||||||
* @param inputSpecFile - Openapi specification input file to calculate its hash.
|
* @param inputSpecFile - Openapi specification input file to calculate its hash.
|
||||||
* Does not take into account if input spec is hosted on remote resource
|
* Does not take into account if input spec is hosted on remote resource
|
||||||
* @return a file with previously calculated hash
|
* @return a file with previously calculated hash
|
||||||
*/
|
*/
|
||||||
private File getHashFile(File inputSpecFile) {
|
private File getHashFile(File inputSpecFile) {
|
||||||
|
@ -94,13 +94,13 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
// THEN
|
// THEN
|
||||||
assertTrue(Files.exists(tempDir.resolve(
|
assertTrue(Files.exists(tempDir.resolve(
|
||||||
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
|
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
|
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
|
||||||
* test that the spec is not regenerated when the hash has not changed.
|
* test that the spec is not regenerated when the hash has not changed.
|
||||||
*/
|
*/
|
||||||
public void testSkipRegenerationForClasspathSpecFileNoChange() throws Exception {
|
public void testSkipRegenerationForClasspathSpecFileNoChange() throws Exception {
|
||||||
//GIVEN
|
//GIVEN
|
||||||
@ -114,7 +114,7 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
/* Check the hash file was created */
|
/* Check the hash file was created */
|
||||||
final Path generatedDir = tempDir.resolve("target/generated-sources/common-maven/remote-openapi");
|
final Path generatedDir = tempDir.resolve("target/generated-sources/common-maven/remote-openapi");
|
||||||
assertTrue(Files.exists(
|
assertTrue(Files.exists(
|
||||||
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
|
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
|
||||||
));
|
));
|
||||||
|
|
||||||
/* Remove the generated source */
|
/* Remove the generated source */
|
||||||
@ -134,7 +134,7 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
|
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
|
||||||
* test that the generated source is regenerated when the hash has changed.
|
* test that the generated source is regenerated when the hash has changed.
|
||||||
*/
|
*/
|
||||||
public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exception {
|
public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exception {
|
||||||
//GIVEN
|
//GIVEN
|
||||||
@ -151,12 +151,12 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
/* Update the hash contents to be a different value, simulating a spec change */
|
/* Update the hash contents to be a different value, simulating a spec change */
|
||||||
Files.write(
|
Files.write(
|
||||||
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
|
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
|
||||||
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
|
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
|
||||||
);
|
);
|
||||||
|
|
||||||
/* Remove the generated source */
|
/* Remove the generated source */
|
||||||
try(Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
|
try (Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
|
||||||
//noinspection ResultOfMethodCallIgnored
|
//noinspection ResultOfMethodCallIgnored
|
||||||
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
|
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
|
||||||
}
|
}
|
||||||
@ -181,7 +181,7 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
// THEN
|
// THEN
|
||||||
assertTrue(Files.exists(
|
assertTrue(Files.exists(
|
||||||
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
|
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -194,8 +194,8 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
// THEN
|
// THEN
|
||||||
List<Artifact> matchingArtifacts = mojo.mavenProject.getAttachedArtifacts().stream()
|
List<Artifact> matchingArtifacts = mojo.mavenProject.getAttachedArtifacts().stream()
|
||||||
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
|
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
assertEquals(1, matchingArtifacts.size());
|
assertEquals(1, matchingArtifacts.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -242,7 +242,7 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
var currentHash = Files.readString(hashFile); // read hash
|
var currentHash = Files.readString(hashFile); // read hash
|
||||||
FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source
|
FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source
|
||||||
Files.writeString( // change schema definition in external file
|
Files.writeString( // change schema definition in external file
|
||||||
tempDir.resolve("schemas/Pet.yaml"),"\n wrapped: true", StandardOpenOption.APPEND
|
tempDir.resolve("schemas/Pet.yaml"), "\n wrapped: true", StandardOpenOption.APPEND
|
||||||
);
|
);
|
||||||
|
|
||||||
// WHEN
|
// WHEN
|
||||||
@ -250,8 +250,8 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
|
|
||||||
// THEN
|
// THEN
|
||||||
assertNotEquals(
|
assertNotEquals(
|
||||||
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
|
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
|
||||||
);
|
);
|
||||||
assertTrue("Src directory should have been regenerated", Files.exists(generatedDir.resolve("src")));
|
assertTrue("Src directory should have been regenerated", Files.exists(generatedDir.resolve("src")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -269,7 +269,7 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private MojoExecution copyWithExecutionId(String executionId, MojoExecution execution) {
|
private MojoExecution copyWithExecutionId(String executionId, MojoExecution execution) {
|
||||||
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
|
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
|
||||||
executionWithId.setConfiguration(execution.getConfiguration());
|
executionWithId.setConfiguration(execution.getConfiguration());
|
||||||
return executionWithId;
|
return executionWithId;
|
||||||
}
|
}
|
||||||
@ -278,18 +278,18 @@ public class CodeGenMojoTest extends BaseTestCase {
|
|||||||
LocalRepository localRepo = new LocalRepository(basedir.resolve("local-repo").toFile());
|
LocalRepository localRepo = new LocalRepository(basedir.resolve("local-repo").toFile());
|
||||||
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
|
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
|
||||||
session.setLocalRepositoryManager(
|
session.setLocalRepositoryManager(
|
||||||
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
|
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
|
||||||
);
|
);
|
||||||
MavenExecutionRequest request = new DefaultMavenExecutionRequest().setBaseDirectory(basedir.toFile());
|
MavenExecutionRequest request = new DefaultMavenExecutionRequest().setBaseDirectory(basedir.toFile());
|
||||||
if (profile != null) {
|
if (profile != null) {
|
||||||
request.addActiveProfile(profile);
|
request.addActiveProfile(profile);
|
||||||
}
|
}
|
||||||
ProjectBuildingRequest configuration = request.getProjectBuildingRequest()
|
ProjectBuildingRequest configuration = request.getProjectBuildingRequest()
|
||||||
.setRepositorySession(session)
|
.setRepositorySession(session)
|
||||||
.setResolveDependencies(true);
|
.setResolveDependencies(true);
|
||||||
MavenProject project = lookup(ProjectBuilder.class)
|
MavenProject project = lookup(ProjectBuilder.class)
|
||||||
.build(basedir.resolve("pom.xml").toFile(), configuration)
|
.build(basedir.resolve("pom.xml").toFile(), configuration)
|
||||||
.getProject();
|
.getProject();
|
||||||
assertNotNull(project);
|
assertNotNull(project);
|
||||||
return project;
|
return project;
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,6 @@ import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
|
|||||||
|
|
||||||
public class CommonMavenProjectStub extends MavenProjectStub {
|
public class CommonMavenProjectStub extends MavenProjectStub {
|
||||||
public CommonMavenProjectStub() {
|
public CommonMavenProjectStub() {
|
||||||
StubUtility.configureStub(this,"common-maven", "common-maven.xml");
|
StubUtility.configureStub(this, "common-maven", "common-maven.xml");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -28,7 +28,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
|||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@ComponentScan(basePackages = { "org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
|
@ComponentScan(basePackages = {"org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
|
||||||
public class OpenAPI2SpringBoot implements CommandLineRunner {
|
public class OpenAPI2SpringBoot implements CommandLineRunner {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -26,14 +26,14 @@ import java.util.Date;
|
|||||||
|
|
||||||
public class RFC3339DateFormat extends ISO8601DateFormat {
|
public class RFC3339DateFormat extends ISO8601DateFormat {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
// Same as ISO8601DateFormat but serializing milliseconds.
|
// Same as ISO8601DateFormat but serializing milliseconds.
|
||||||
@Override
|
@Override
|
||||||
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
|
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
|
||||||
String value = ISO8601Utils.format(date, true);
|
String value = ISO8601Utils.format(date, true);
|
||||||
toAppendTo.append(value);
|
toAppendTo.append(value);
|
||||||
return toAppendTo;
|
return toAppendTo;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -17,16 +17,15 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen.online.api;
|
package org.openapitools.codegen.online.api;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import javax.servlet.*;
|
import javax.servlet.*;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
|
||||||
public class ApiOriginFilter implements javax.servlet.Filter {
|
public class ApiOriginFilter implements javax.servlet.Filter {
|
||||||
@Override
|
@Override
|
||||||
public void doFilter(ServletRequest request, ServletResponse response,
|
public void doFilter(ServletRequest request, ServletResponse response,
|
||||||
FilterChain chain) throws IOException, ServletException {
|
FilterChain chain) throws IOException, ServletException {
|
||||||
HttpServletResponse res = (HttpServletResponse) response;
|
HttpServletResponse res = (HttpServletResponse) response;
|
||||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||||
|
@ -42,9 +42,9 @@ import java.util.Map;
|
|||||||
public interface GenApi {
|
public interface GenApi {
|
||||||
GenApiDelegate getDelegate();
|
GenApiDelegate getDelegate();
|
||||||
|
|
||||||
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags={ "clients", })
|
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags = {"clients",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
|
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
|
||||||
@RequestMapping(value = "/gen/clients",
|
@RequestMapping(value = "/gen/clients",
|
||||||
method = RequestMethod.GET)
|
method = RequestMethod.GET)
|
||||||
default ResponseEntity<List<String>> clientOptions() {
|
default ResponseEntity<List<String>> clientOptions() {
|
||||||
@ -52,62 +52,62 @@ public interface GenApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags={ "clients","servers", })
|
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags = {"clients", "servers",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class) })
|
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class)})
|
||||||
@RequestMapping(value = "/gen/download/{fileId}",
|
@RequestMapping(value = "/gen/download/{fileId}",
|
||||||
produces = { "application/octet-stream" },
|
produces = {"application/octet-stream"},
|
||||||
method = RequestMethod.GET)
|
method = RequestMethod.GET)
|
||||||
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "",required=true) @PathVariable("fileId") String fileId) {
|
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "", required = true) @PathVariable("fileId") String fileId) {
|
||||||
return getDelegate().downloadFile(fileId);
|
return getDelegate().downloadFile(fileId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags={ "clients", })
|
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags = {"clients",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
|
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
|
||||||
@RequestMapping(value = "/gen/clients/{language}",
|
@RequestMapping(value = "/gen/clients/{language}",
|
||||||
method = RequestMethod.POST)
|
method = RequestMethod.POST)
|
||||||
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language,@ApiParam(value = "Configuration for building the client library" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
|
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language, @ApiParam(value = "Configuration for building the client library", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
|
||||||
return getDelegate().generateClient(language, generatorInput);
|
return getDelegate().generateClient(language, generatorInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags={ "servers", })
|
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags = {"servers",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
|
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
|
||||||
@RequestMapping(value = "/gen/servers/{framework}",
|
@RequestMapping(value = "/gen/servers/{framework}",
|
||||||
method = RequestMethod.POST)
|
method = RequestMethod.POST)
|
||||||
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework",required=true) @PathVariable("framework") String framework,@ApiParam(value = "parameters" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
|
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework", required = true) @PathVariable("framework") String framework, @ApiParam(value = "parameters", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
|
||||||
return getDelegate().generateServerForLanguage(framework, generatorInput);
|
return getDelegate().generateServerForLanguage(framework, generatorInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags={ "clients", })
|
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags = {"clients",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation") })
|
@ApiResponse(code = 200, message = "successful operation")})
|
||||||
@RequestMapping(value = "/gen/clients/{language}",
|
@RequestMapping(value = "/gen/clients/{language}",
|
||||||
produces = { "application/json" },
|
produces = {"application/json"},
|
||||||
method = RequestMethod.GET)
|
method = RequestMethod.GET)
|
||||||
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language) {
|
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language) {
|
||||||
return getDelegate().getClientOptions(language);
|
return getDelegate().getClientOptions(language);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags={ "servers", })
|
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags = {"servers",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation") })
|
@ApiResponse(code = 200, message = "successful operation")})
|
||||||
@RequestMapping(value = "/gen/servers/{framework}",
|
@RequestMapping(value = "/gen/servers/{framework}",
|
||||||
produces = { "application/json" },
|
produces = {"application/json"},
|
||||||
method = RequestMethod.GET)
|
method = RequestMethod.GET)
|
||||||
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework",required=true) @PathVariable("framework") String framework) {
|
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework", required = true) @PathVariable("framework") String framework) {
|
||||||
return getDelegate().getServerOptions(framework);
|
return getDelegate().getServerOptions(framework);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags={ "servers", })
|
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags = {"servers",})
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
|
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
|
||||||
@RequestMapping(value = "/gen/servers",
|
@RequestMapping(value = "/gen/servers",
|
||||||
method = RequestMethod.GET)
|
method = RequestMethod.GET)
|
||||||
default ResponseEntity<List<String>> serverOptions() {
|
default ResponseEntity<List<String>> serverOptions() {
|
||||||
|
@ -42,12 +42,12 @@ public interface GenApiDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see GenApi#clientOptions
|
|
||||||
* @return A {@link ResponseEntity} listing options for the target client generator.
|
* @return A {@link ResponseEntity} listing options for the target client generator.
|
||||||
|
* @see GenApi#clientOptions
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<List<String>> clientOptions() {
|
default ResponseEntity<List<String>> clientOptions() {
|
||||||
getRequest().ifPresent(request -> {
|
getRequest().ifPresent(request -> {
|
||||||
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
||||||
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
||||||
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
|
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
|
||||||
break;
|
break;
|
||||||
@ -60,24 +60,24 @@ public interface GenApiDelegate {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param fileId The unique id of the file, provided in a {@link ResponseCode} response.
|
* @param fileId The unique id of the file, provided in a {@link ResponseCode} response.
|
||||||
* @see GenApi#downloadFile
|
|
||||||
* @return A {@link ResponseEntity} of the requested {@link Resource}.
|
* @return A {@link ResponseEntity} of the requested {@link Resource}.
|
||||||
|
* @see GenApi#downloadFile
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<Resource> downloadFile(String fileId) {
|
default ResponseEntity<Resource> downloadFile(String fileId) {
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param language The target generator (language is a misnomer here, but kept for API consistency).
|
* @param language The target generator (language is a misnomer here, but kept for API consistency).
|
||||||
* @param generatorInput The configuration settings to be used during client generation.
|
* @param generatorInput The configuration settings to be used during client generation.
|
||||||
* @see GenApi#generateClient
|
|
||||||
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested client code.
|
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested client code.
|
||||||
|
* @see GenApi#generateClient
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<ResponseCode> generateClient( String language,
|
default ResponseEntity<ResponseCode> generateClient(String language,
|
||||||
GeneratorInput generatorInput) {
|
GeneratorInput generatorInput) {
|
||||||
getRequest().ifPresent(request -> {
|
getRequest().ifPresent(request -> {
|
||||||
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
||||||
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
||||||
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
|
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
|
||||||
break;
|
break;
|
||||||
@ -89,15 +89,15 @@ public interface GenApiDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
|
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
|
||||||
* @param generatorInput The configuration settings to be used during server generation.
|
* @param generatorInput The configuration settings to be used during server generation.
|
||||||
* @see GenApi#generateServerForLanguage
|
|
||||||
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested server code.
|
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested server code.
|
||||||
|
* @see GenApi#generateServerForLanguage
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<ResponseCode> generateServerForLanguage( String framework,
|
default ResponseEntity<ResponseCode> generateServerForLanguage(String framework,
|
||||||
GeneratorInput generatorInput) {
|
GeneratorInput generatorInput) {
|
||||||
getRequest().ifPresent(request -> {
|
getRequest().ifPresent(request -> {
|
||||||
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
||||||
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
||||||
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
|
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
|
||||||
break;
|
break;
|
||||||
@ -110,31 +110,31 @@ public interface GenApiDelegate {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param language The target generator (language is a misnomer here, but kept for API consistency).
|
* @param language The target generator (language is a misnomer here, but kept for API consistency).
|
||||||
* @see GenApi#getClientOptions
|
|
||||||
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by language (generator name).
|
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by language (generator name).
|
||||||
|
* @see GenApi#getClientOptions
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
|
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
|
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
|
||||||
* @see GenApi#getServerOptions
|
|
||||||
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by framework (generator name).
|
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by framework (generator name).
|
||||||
|
* @see GenApi#getServerOptions
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<Map<String, CliOption>> getServerOptions( String framework) {
|
default ResponseEntity<Map<String, CliOption>> getServerOptions(String framework) {
|
||||||
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see GenApi#serverOptions
|
|
||||||
* @return A {@link ResponseEntity} listing options for the target server generator.
|
* @return A {@link ResponseEntity} listing options for the target server generator.
|
||||||
|
* @see GenApi#serverOptions
|
||||||
*/
|
*/
|
||||||
default ResponseEntity<List<String>> serverOptions() {
|
default ResponseEntity<List<String>> serverOptions() {
|
||||||
getRequest().ifPresent(request -> {
|
getRequest().ifPresent(request -> {
|
||||||
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
|
||||||
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
|
||||||
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
|
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
|
||||||
break;
|
break;
|
||||||
|
@ -18,6 +18,9 @@
|
|||||||
package org.openapitools.codegen.online.configuration;
|
package org.openapitools.codegen.online.configuration;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
@ -28,17 +31,14 @@ import springfox.documentation.service.Contact;
|
|||||||
import springfox.documentation.spi.DocumentationType;
|
import springfox.documentation.spi.DocumentationType;
|
||||||
import springfox.documentation.spring.web.plugins.Docket;
|
import springfox.documentation.spring.web.plugins.Docket;
|
||||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.HashSet;
|
|
||||||
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ -59,22 +59,22 @@ public class OpenAPIDocumentationConfig {
|
|||||||
String version = properties.getProperty("version", "unknown");
|
String version = properties.getProperty("version", "unknown");
|
||||||
|
|
||||||
return new ApiInfoBuilder()
|
return new ApiInfoBuilder()
|
||||||
.title("OpenAPI Generator Online")
|
.title("OpenAPI Generator Online")
|
||||||
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
|
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
|
||||||
.license("Apache 2.0")
|
.license("Apache 2.0")
|
||||||
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
|
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
|
||||||
.termsOfServiceUrl("")
|
.termsOfServiceUrl("")
|
||||||
.version(version)
|
.version(version)
|
||||||
.contact(new Contact("","", ""))
|
.contact(new Contact("", "", ""))
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public Docket customImplementation(){
|
public Docket customImplementation() {
|
||||||
Docket docket = new Docket(DocumentationType.SWAGGER_2)
|
Docket docket = new Docket(DocumentationType.SWAGGER_2)
|
||||||
.select()
|
.select()
|
||||||
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
|
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
|
||||||
.build()
|
.build()
|
||||||
.forCodeGeneration(true)
|
.forCodeGeneration(true)
|
||||||
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
|
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
|
||||||
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
|
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
|
||||||
@ -99,7 +99,7 @@ public class OpenAPIDocumentationConfig {
|
|||||||
docket.host(authority);
|
docket.host(authority);
|
||||||
}
|
}
|
||||||
docket.pathMapping(hostURI.getPath());
|
docket.pathMapping(hostURI.getPath());
|
||||||
} catch(URISyntaxException e) {
|
} catch (URISyntaxException e) {
|
||||||
LOGGER.warn("Could not parse configured GENERATOR_HOST '" + hostString + "': " + e.getMessage());
|
LOGGER.warn("Could not parse configured GENERATOR_HOST '" + hostString + "': " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,8 @@ public class ApiResponse {
|
|||||||
@Getter String type;
|
@Getter String type;
|
||||||
@Getter String message;
|
@Getter String message;
|
||||||
|
|
||||||
public ApiResponse() {}
|
public ApiResponse() {
|
||||||
|
}
|
||||||
|
|
||||||
public ApiResponse(int code, String message) {
|
public ApiResponse(int code, String message) {
|
||||||
this.code = code;
|
this.code = code;
|
||||||
|
@ -20,7 +20,8 @@ package org.openapitools.codegen.online.model;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter
|
||||||
|
@Setter
|
||||||
public class Generated {
|
public class Generated {
|
||||||
private String filename;
|
private String filename;
|
||||||
private String friendlyName;
|
private String friendlyName;
|
||||||
|
@ -22,7 +22,9 @@ import lombok.AllArgsConstructor;
|
|||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
@Setter @NoArgsConstructor @AllArgsConstructor
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class ResponseCode {
|
public class ResponseCode {
|
||||||
private String code;
|
private String code;
|
||||||
private String link;
|
private String link;
|
||||||
|
@ -22,11 +22,7 @@ import io.swagger.parser.OpenAPIParser;
|
|||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
||||||
import io.swagger.v3.parser.core.models.ParseOptions;
|
import io.swagger.v3.parser.core.models.ParseOptions;
|
||||||
import org.openapitools.codegen.CliOption;
|
import org.openapitools.codegen.*;
|
||||||
import org.openapitools.codegen.ClientOptInput;
|
|
||||||
import org.openapitools.codegen.CodegenConfig;
|
|
||||||
import org.openapitools.codegen.CodegenConfigLoader;
|
|
||||||
import org.openapitools.codegen.DefaultGenerator;
|
|
||||||
import org.openapitools.codegen.online.model.GeneratorInput;
|
import org.openapitools.codegen.online.model.GeneratorInput;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -35,11 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class Generator {
|
public class Generator {
|
||||||
private static Logger LOGGER = LoggerFactory.getLogger(Generator.class);
|
private static Logger LOGGER = LoggerFactory.getLogger(Generator.class);
|
||||||
@ -49,7 +41,7 @@ public class Generator {
|
|||||||
try {
|
try {
|
||||||
config = CodegenConfigLoader.forName(language);
|
config = CodegenConfigLoader.forName(language);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT, "Unsupported target %s supplied. %s",
|
||||||
language, e));
|
language, e));
|
||||||
}
|
}
|
||||||
Map<String, CliOption> map = new LinkedHashMap<>();
|
Map<String, CliOption> map = new LinkedHashMap<>();
|
||||||
@ -82,7 +74,7 @@ public class Generator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static String generate(String language, GeneratorInput opts, Type type) {
|
private static String generate(String language, GeneratorInput opts, Type type) {
|
||||||
LOGGER.debug(String.format(Locale.ROOT,"generate %s for %s", type.getTypeName(), language));
|
LOGGER.debug(String.format(Locale.ROOT, "generate %s for %s", type.getTypeName(), language));
|
||||||
if (opts == null) {
|
if (opts == null) {
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied");
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied");
|
||||||
}
|
}
|
||||||
@ -141,13 +133,13 @@ public class Generator {
|
|||||||
codegenConfig.additionalProperties().put("openAPI", openapi);
|
codegenConfig.additionalProperties().put("openAPI", openapi);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()){
|
if (opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()) {
|
||||||
for(String rule: opts.getOpenapiNormalizer()){
|
for (String rule : opts.getOpenapiNormalizer()) {
|
||||||
String[] ruleOperands = rule.split("=");
|
String[] ruleOperands = rule.split("=");
|
||||||
if(ruleOperands.length != 2) {
|
if (ruleOperands.length != 2) {
|
||||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "In rule: " + rule + "the operands were not provided in the form of <Rule>=<Value>");
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "In rule: " + rule + "the operands were not provided in the form of <Rule>=<Value>");
|
||||||
}
|
}
|
||||||
codegenConfig.openapiNormalizer().put(ruleOperands[0],ruleOperands[1]);
|
codegenConfig.openapiNormalizer().put(ruleOperands[0], ruleOperands[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,12 +17,7 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen.online.service;
|
package org.openapitools.codegen.online.service;
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
import java.io.*;
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileNotFoundException;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
@ -32,7 +27,6 @@ import java.util.zip.ZipOutputStream;
|
|||||||
* sub files and sub directories, recursively.
|
* sub files and sub directories, recursively.
|
||||||
*
|
*
|
||||||
* @author Ha Minh Nam
|
* @author Ha Minh Nam
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ZipUtil {
|
public class ZipUtil {
|
||||||
/**
|
/**
|
||||||
@ -43,10 +37,10 @@ public class ZipUtil {
|
|||||||
/**
|
/**
|
||||||
* Compresses a collection of files to a destination zip file.
|
* Compresses a collection of files to a destination zip file.
|
||||||
*
|
*
|
||||||
* @param listFiles A collection of files and directories
|
* @param listFiles A collection of files and directories
|
||||||
* @param destZipFile The path of the destination zip file
|
* @param destZipFile The path of the destination zip file
|
||||||
* @throws FileNotFoundException if file not found
|
* @throws FileNotFoundException if file not found
|
||||||
* @throws IOException if IO exception occurs
|
* @throws IOException if IO exception occurs
|
||||||
*/
|
*/
|
||||||
public void compressFiles(List<File> listFiles, String destZipFile)
|
public void compressFiles(List<File> listFiles, String destZipFile)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
@ -69,11 +63,11 @@ public class ZipUtil {
|
|||||||
/**
|
/**
|
||||||
* Adds a directory to the current zip output stream.
|
* Adds a directory to the current zip output stream.
|
||||||
*
|
*
|
||||||
* @param folder the directory to be added
|
* @param folder the directory to be added
|
||||||
* @param parentFolder the path of parent directory
|
* @param parentFolder the path of parent directory
|
||||||
* @param zos the current zip output stream
|
* @param zos the current zip output stream
|
||||||
* @throws FileNotFoundException if file not found
|
* @throws FileNotFoundException if file not found
|
||||||
* @throws IOException if IO exception occurs
|
* @throws IOException if IO exception occurs
|
||||||
*/
|
*/
|
||||||
private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos)
|
private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos)
|
||||||
throws FileNotFoundException, IOException {
|
throws FileNotFoundException, IOException {
|
||||||
@ -103,9 +97,9 @@ public class ZipUtil {
|
|||||||
* Adds a file to the current zip output stream.
|
* Adds a file to the current zip output stream.
|
||||||
*
|
*
|
||||||
* @param file the file to be added
|
* @param file the file to be added
|
||||||
* @param zos the current zip output stream
|
* @param zos the current zip output stream
|
||||||
* @throws FileNotFoundException if file not found
|
* @throws FileNotFoundException if file not found
|
||||||
* @throws IOException if IO exception occurs
|
* @throws IOException if IO exception occurs
|
||||||
*/
|
*/
|
||||||
private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException,
|
private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException,
|
||||||
IOException {
|
IOException {
|
||||||
|
@ -88,8 +88,8 @@ public class GenApiControllerTest {
|
|||||||
|
|
||||||
private void generateAndDownload(String type, String name) throws Exception {
|
private void generateAndDownload(String type, String name) throws Exception {
|
||||||
String result = mockMvc.perform(post("http://test.com:1234/api/gen/" + type + "/" + name)
|
String result = mockMvc.perform(post("http://test.com:1234/api/gen/" + type + "/" + name)
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
|
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||||
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
|
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
|
||||||
@ -107,11 +107,11 @@ public class GenApiControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void generateWIthForwardedHeaders() throws Exception {
|
public void generateWIthForwardedHeaders() throws Exception {
|
||||||
String result = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
|
String result = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.header("X-Forwarded-Proto", "https")
|
.header("X-Forwarded-Proto", "https")
|
||||||
.header("X-Forwarded-Host", "forwarded.com")
|
.header("X-Forwarded-Host", "forwarded.com")
|
||||||
.header("X-Forwarded-Port", "5678")
|
.header("X-Forwarded-Port", "5678")
|
||||||
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
|
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||||
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
|
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
|
||||||
@ -141,8 +141,8 @@ public class GenApiControllerTest {
|
|||||||
String withoutOpenAPINormalizer = "{\"openAPIUrl\":\"https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml\",\"options\":{},\"spec\":{}}";
|
String withoutOpenAPINormalizer = "{\"openAPIUrl\":\"https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml\",\"options\":{},\"spec\":{}}";
|
||||||
|
|
||||||
String responseOfNormalized = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
|
String responseOfNormalized = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.content(withOpenAPINormalizer))
|
.content(withOpenAPINormalizer))
|
||||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
String codeOfNormalized = new ObjectMapper().readValue(responseOfNormalized, ResponseCode.class).getCode();
|
String codeOfNormalized = new ObjectMapper().readValue(responseOfNormalized, ResponseCode.class).getCode();
|
||||||
Long lengthOfNormalized = Long.parseLong(mockMvc.perform(get("http://test.com:1234/api/gen/download/" + codeOfNormalized))
|
Long lengthOfNormalized = Long.parseLong(mockMvc.perform(get("http://test.com:1234/api/gen/download/" + codeOfNormalized))
|
||||||
@ -159,7 +159,7 @@ public class GenApiControllerTest {
|
|||||||
.andExpect(content().contentType("application/zip"))
|
.andExpect(content().contentType("application/zip"))
|
||||||
.andExpect(status().isOk()).andReturn().getResponse().getHeader("Content-Length"));
|
.andExpect(status().isOk()).andReturn().getResponse().getHeader("Content-Length"));
|
||||||
|
|
||||||
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized,"Using the normalizer should result in a smaller or equal file size");
|
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized, "Using the normalizer should result in a smaller or equal file size");
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -60,7 +60,7 @@ public class CliOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void setOptValue(String optValue) {
|
public void setOptValue(String optValue) {
|
||||||
if (this.enumValues!=null && this.enumValues.containsKey(optValue)) {
|
if (this.enumValues != null && this.enumValues.containsKey(optValue)) {
|
||||||
this.optValue = optValue;
|
this.optValue = optValue;
|
||||||
} else {
|
} else {
|
||||||
this.optValue = null;
|
this.optValue = null;
|
||||||
@ -88,7 +88,7 @@ public class CliOption {
|
|||||||
/**
|
/**
|
||||||
* Create new boolean command line option with a default of false
|
* Create new boolean command line option with a default of false
|
||||||
*
|
*
|
||||||
* @param opt Option name
|
* @param opt Option name
|
||||||
* @param description Option description
|
* @param description Option description
|
||||||
* @return the CliOption created
|
* @return the CliOption created
|
||||||
*/
|
*/
|
||||||
@ -99,8 +99,8 @@ public class CliOption {
|
|||||||
/**
|
/**
|
||||||
* Create new boolean command line option with the provided value as default
|
* Create new boolean command line option with the provided value as default
|
||||||
*
|
*
|
||||||
* @param opt Option name
|
* @param opt Option name
|
||||||
* @param description Option description
|
* @param description Option description
|
||||||
* @param defaultValue the default value to use if option not specified
|
* @param defaultValue the default value to use if option not specified
|
||||||
* @return the CliOption created
|
* @return the CliOption created
|
||||||
*/
|
*/
|
||||||
@ -115,7 +115,7 @@ public class CliOption {
|
|||||||
@JsonIgnore
|
@JsonIgnore
|
||||||
public String getOptionHelp() {
|
public String getOptionHelp() {
|
||||||
StringBuilder sb = new StringBuilder(description);
|
StringBuilder sb = new StringBuilder(description);
|
||||||
if(defaultValue != null) {
|
if (defaultValue != null) {
|
||||||
sb.append(" (Default: ").append(defaultValue).append(")");
|
sb.append(" (Default: ").append(defaultValue).append(")");
|
||||||
}
|
}
|
||||||
if (enumValues != null) {
|
if (enumValues != null) {
|
||||||
|
@ -19,7 +19,6 @@ package org.openapitools.codegen;
|
|||||||
|
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
import io.swagger.v3.parser.core.models.AuthorizationValue;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import org.openapitools.codegen.api.TemplateDefinition;
|
import org.openapitools.codegen.api.TemplateDefinition;
|
||||||
import org.openapitools.codegen.auth.AuthParser;
|
import org.openapitools.codegen.auth.AuthParser;
|
||||||
@ -84,8 +83,8 @@ public class ClientOptInput {
|
|||||||
/**
|
/**
|
||||||
* Sets the generator/config instance
|
* Sets the generator/config instance
|
||||||
*
|
*
|
||||||
* @deprecated use {@link #config(CodegenConfig)} instead
|
|
||||||
* @param config codegen config
|
* @param config codegen config
|
||||||
|
* @deprecated use {@link #config(CodegenConfig)} instead
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public void setConfig(CodegenConfig config) {
|
public void setConfig(CodegenConfig config) {
|
||||||
@ -118,8 +117,8 @@ public class ClientOptInput {
|
|||||||
/**
|
/**
|
||||||
* Sets the OpenAPI document
|
* Sets the OpenAPI document
|
||||||
*
|
*
|
||||||
* @deprecated use {@link #openAPI(OpenAPI)} instead
|
|
||||||
* @param openAPI the specification
|
* @param openAPI the specification
|
||||||
|
* @deprecated use {@link #openAPI(OpenAPI)} instead
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public void setOpenAPI(OpenAPI openAPI) {
|
public void setOpenAPI(OpenAPI openAPI) {
|
||||||
|
@ -38,6 +38,7 @@ public class CodegenCallback {
|
|||||||
return Objects.equals(that.expression, expression) &&
|
return Objects.equals(that.expression, expression) &&
|
||||||
Objects.equals(that.requests, requests) && Objects.equals(that.vendorExtensions, vendorExtensions);
|
Objects.equals(that.requests, requests) && Objects.equals(that.vendorExtensions, vendorExtensions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(expression, requests, vendorExtensions);
|
return Objects.hash(expression, requests, vendorExtensions);
|
||||||
|
@ -19,9 +19,11 @@ package org.openapitools.codegen;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter
|
||||||
|
@Setter
|
||||||
public class CodegenComposedSchemas {
|
public class CodegenComposedSchemas {
|
||||||
private List<CodegenProperty> allOf;
|
private List<CodegenProperty> allOf;
|
||||||
private List<CodegenProperty> oneOf;
|
private List<CodegenProperty> oneOf;
|
||||||
|
@ -372,9 +372,9 @@ public class CodegenConstants {
|
|||||||
|
|
||||||
public static final String GENERATE_ALIAS_AS_MODEL = "generateAliasAsModel";
|
public static final String GENERATE_ALIAS_AS_MODEL = "generateAliasAsModel";
|
||||||
public static final String GENERATE_ALIAS_AS_MODEL_DESC = "Generate model implementation for aliases to map and array schemas. " +
|
public static final String GENERATE_ALIAS_AS_MODEL_DESC = "Generate model implementation for aliases to map and array schemas. " +
|
||||||
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
|
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
|
||||||
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
|
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
|
||||||
"An 'array' schema is a list of sub schemas in a OAS document";
|
"An 'array' schema is a list of sub schemas in a OAS document";
|
||||||
|
|
||||||
public static final String USE_COMPARE_NET_OBJECTS = "useCompareNetObjects";
|
public static final String USE_COMPARE_NET_OBJECTS = "useCompareNetObjects";
|
||||||
public static final String USE_COMPARE_NET_OBJECTS_DESC = "Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.";
|
public static final String USE_COMPARE_NET_OBJECTS_DESC = "Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.";
|
||||||
@ -405,16 +405,16 @@ public class CodegenConstants {
|
|||||||
|
|
||||||
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT = "disallowAdditionalPropertiesIfNotPresent";
|
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT = "disallowAdditionalPropertiesIfNotPresent";
|
||||||
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC =
|
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC =
|
||||||
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
|
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
|
||||||
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
|
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
|
||||||
|
|
||||||
public static final String UNSUPPORTED_V310_SPEC_MSG =
|
public static final String UNSUPPORTED_V310_SPEC_MSG =
|
||||||
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
|
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
|
||||||
|
|
||||||
public static final String ENUM_UNKNOWN_DEFAULT_CASE = "enumUnknownDefaultCase";
|
public static final String ENUM_UNKNOWN_DEFAULT_CASE = "enumUnknownDefaultCase";
|
||||||
public static final String ENUM_UNKNOWN_DEFAULT_CASE_DESC =
|
public static final String ENUM_UNKNOWN_DEFAULT_CASE_DESC =
|
||||||
"If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response." +
|
"If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response." +
|
||||||
"With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.";
|
"With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.";
|
||||||
|
|
||||||
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
|
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
|
||||||
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.";
|
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.";
|
||||||
@ -438,7 +438,7 @@ public class CodegenConstants {
|
|||||||
public static final String FASTAPI_IMPLEMENTATION_PACKAGE = "fastapiImplementationPackage";
|
public static final String FASTAPI_IMPLEMENTATION_PACKAGE = "fastapiImplementationPackage";
|
||||||
|
|
||||||
public static final String WITH_XML = "withXml";
|
public static final String WITH_XML = "withXml";
|
||||||
|
|
||||||
public static final String WITH_GO_MOD = "withGoMod";
|
public static final String WITH_GO_MOD = "withGoMod";
|
||||||
|
|
||||||
public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON";
|
public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON";
|
||||||
|
@ -8,7 +8,7 @@ import java.util.*;
|
|||||||
/**
|
/**
|
||||||
* This class encapsulates the OpenAPI discriminator construct, as specified at
|
* This class encapsulates the OpenAPI discriminator construct, as specified at
|
||||||
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject.
|
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject.
|
||||||
*
|
* <p>
|
||||||
* When request bodies or response payloads may be one of a number of different schemas,
|
* When request bodies or response payloads may be one of a number of different schemas,
|
||||||
* a discriminator object can be used to aid in serialization, deserialization, and validation.
|
* a discriminator object can be used to aid in serialization, deserialization, and validation.
|
||||||
* The discriminator is a specific object in a schema which is used to inform the consumer of
|
* The discriminator is a specific object in a schema which is used to inform the consumer of
|
||||||
@ -57,18 +57,18 @@ public class CodegenDiscriminator {
|
|||||||
public void setIsEnum(boolean isEnum) {
|
public void setIsEnum(boolean isEnum) {
|
||||||
this.isEnum = isEnum;
|
this.isEnum = isEnum;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An object to hold discriminator mappings between payload values and schema names or
|
* An object to hold discriminator mappings between payload values and schema names or
|
||||||
* references.
|
* references.
|
||||||
*
|
* <p>
|
||||||
* In the OpenAPI document, the discriminator "mapping" attribute is optional.
|
* In the OpenAPI document, the discriminator "mapping" attribute is optional.
|
||||||
* In scenarios where the value of the discriminator field does not match the schema name
|
* In scenarios where the value of the discriminator field does not match the schema name
|
||||||
* or implicit mapping is not possible, an optional mapping definition MAY be used.
|
* or implicit mapping is not possible, an optional mapping definition MAY be used.
|
||||||
* In OpenAPITools codegen, the MappedModel is the union of all the discriminator mappings,
|
* In OpenAPITools codegen, the MappedModel is the union of all the discriminator mappings,
|
||||||
* both explicitly defined in the OpenAPI document and inherited from oneOf/allOf/anyOf.
|
* both explicitly defined in the OpenAPI document and inherited from oneOf/allOf/anyOf.
|
||||||
*/
|
*/
|
||||||
public static class MappedModel implements Comparable<MappedModel>{
|
public static class MappedModel implements Comparable<MappedModel> {
|
||||||
// The value of the discriminator property in the payload.
|
// The value of the discriminator property in the payload.
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
private String mappingName;
|
private String mappingName;
|
||||||
|
@ -8,7 +8,8 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@Getter public class CodegenMediaType {
|
@Getter
|
||||||
|
public class CodegenMediaType {
|
||||||
private CodegenProperty schema;
|
private CodegenProperty schema;
|
||||||
private LinkedHashMap<String, CodegenEncoding> encoding;
|
private LinkedHashMap<String, CodegenEncoding> encoding;
|
||||||
private HashMap<String, SchemaTestCase> testCases = new HashMap<>();
|
private HashMap<String, SchemaTestCase> testCases = new HashMap<>();
|
||||||
@ -47,7 +48,7 @@ import java.util.Objects;
|
|||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
if (o == null || getClass() != o.getClass()) return false;
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
CodegenMediaType that = (CodegenMediaType) o;
|
CodegenMediaType that = (CodegenMediaType) o;
|
||||||
return Objects.equals(schema,that.getSchema()) &&
|
return Objects.equals(schema, that.getSchema()) &&
|
||||||
Objects.equals(encoding, that.getEncoding()) &&
|
Objects.equals(encoding, that.getEncoding()) &&
|
||||||
Objects.equals(vendorExtensions, that.vendorExtensions);
|
Objects.equals(vendorExtensions, that.vendorExtensions);
|
||||||
}
|
}
|
||||||
|
@ -19,13 +19,12 @@ package org.openapitools.codegen;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
import io.swagger.v3.oas.models.ExternalDocumentation;
|
import io.swagger.v3.oas.models.ExternalDocumentation;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CodegenModel represents a schema object in a OpenAPI document.
|
* CodegenModel represents a schema object in a OpenAPI document.
|
||||||
*/
|
*/
|
||||||
@ -85,39 +84,39 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
public String unescapedDescription;
|
public String unescapedDescription;
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
|
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
|
||||||
* The list of all possible schema discriminator mapping values is obtained
|
* The list of all possible schema discriminator mapping values is obtained
|
||||||
* from explicit discriminator mapping values in the OpenAPI document, and from
|
* from explicit discriminator mapping values in the OpenAPI document, and from
|
||||||
* inherited discriminators through oneOf, allOf, anyOf.
|
* inherited discriminators through oneOf, allOf, anyOf.
|
||||||
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
|
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
|
||||||
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
|
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
|
||||||
* In the 'Pet' schema, the supported discriminator mapping values for the
|
* In the 'Pet' schema, the supported discriminator mapping values for the
|
||||||
* 'objectType' properties are 'Dog' and 'Cat'.
|
* 'objectType' properties are 'Dog' and 'Cat'.
|
||||||
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
|
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
|
||||||
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
|
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
|
||||||
* Pet:
|
* Pet:
|
||||||
* type: object
|
* type: object
|
||||||
* discriminator:
|
* discriminator:
|
||||||
* propertyName: objectType
|
* propertyName: objectType
|
||||||
* required:
|
* required:
|
||||||
* - objectType
|
* - objectType
|
||||||
* properties:
|
* properties:
|
||||||
* objectType:
|
* objectType:
|
||||||
* type: string
|
* type: string
|
||||||
* Dog:
|
* Dog:
|
||||||
* allOf:
|
* allOf:
|
||||||
* - $ref: '#/components/schemas/Pet'
|
* - $ref: '#/components/schemas/Pet'
|
||||||
* - type: object
|
* - type: object
|
||||||
* properties:
|
* properties:
|
||||||
* p1:
|
* p1:
|
||||||
* type: string
|
* type: string
|
||||||
* Cat:
|
* Cat:
|
||||||
* allOf:
|
* allOf:
|
||||||
* - $ref: '#/components/schemas/Pet'
|
* - $ref: '#/components/schemas/Pet'
|
||||||
* - type: object
|
* - type: object
|
||||||
* properties:
|
* properties:
|
||||||
* p2:
|
* p2:
|
||||||
* type: string
|
* type: string
|
||||||
*
|
*
|
||||||
* @return the discriminator.
|
* @return the discriminator.
|
||||||
*/
|
*/
|
||||||
@ -174,7 +173,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
public boolean isArray;
|
public boolean isArray;
|
||||||
public boolean hasChildren;
|
public boolean hasChildren;
|
||||||
public boolean isMap;
|
public boolean isMap;
|
||||||
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
|
/**
|
||||||
|
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
|
||||||
|
*/
|
||||||
public boolean isOptional;
|
public boolean isOptional;
|
||||||
public boolean isNull;
|
public boolean isNull;
|
||||||
public boolean isVoid = false;
|
public boolean isVoid = false;
|
||||||
@ -208,7 +209,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
/**
|
/**
|
||||||
* The type of the value for the additionalProperties keyword in the OAS document.
|
* The type of the value for the additionalProperties keyword in the OAS document.
|
||||||
* Used in map like objects, including composed schemas.
|
* Used in map like objects, including composed schemas.
|
||||||
*
|
* <p>
|
||||||
* In most programming languages, the additional (undeclared) properties are stored
|
* In most programming languages, the additional (undeclared) properties are stored
|
||||||
* in a map data structure, such as HashMap in Java, map in golang, or a dict in Python.
|
* in a map data structure, such as HashMap in Java, map in golang, or a dict in Python.
|
||||||
* There are multiple ways to implement the additionalProperties keyword, depending
|
* There are multiple ways to implement the additionalProperties keyword, depending
|
||||||
@ -218,24 +219,23 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
* In that case 'CodegenModel.parent' is set to represent the class hierarchy.
|
* In that case 'CodegenModel.parent' is set to represent the class hierarchy.
|
||||||
* Another way is to use CodegenModel.additionalPropertiesType. A code generator
|
* Another way is to use CodegenModel.additionalPropertiesType. A code generator
|
||||||
* such as Python does not use class inheritance to model additional properties.
|
* such as Python does not use class inheritance to model additional properties.
|
||||||
*
|
* <p>
|
||||||
* For example, in the OAS schema below, the schema has a declared 'id' property
|
* For example, in the OAS schema below, the schema has a declared 'id' property
|
||||||
* and additional, undeclared properties of type 'integer' are allowed.
|
* and additional, undeclared properties of type 'integer' are allowed.
|
||||||
*
|
* <p>
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
* id:
|
* id:
|
||||||
* type: integer
|
* type: integer
|
||||||
* additionalProperties:
|
* additionalProperties:
|
||||||
* type: integer
|
* type: integer
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
public String additionalPropertiesType;
|
public String additionalPropertiesType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True if additionalProperties is set to true (boolean value), any type, free form object, etc
|
* True if additionalProperties is set to true (boolean value), any type, free form object, etc
|
||||||
*
|
* <p>
|
||||||
* TODO: we may rename this to isAdditionalPropertiesEnabled or something
|
* TODO: we may rename this to isAdditionalPropertiesEnabled or something
|
||||||
* else to avoid confusions
|
* else to avoid confusions
|
||||||
*/
|
*/
|
||||||
@ -758,14 +758,22 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean getIsUuid() { return isUuid; }
|
public boolean getIsUuid() {
|
||||||
|
return isUuid;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setIsUuid(boolean isUuid) { this.isUuid = isUuid; }
|
public void setIsUuid(boolean isUuid) {
|
||||||
|
this.isUuid = isUuid;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean getIsUri() { return isUri; }
|
public boolean getIsUri() {
|
||||||
|
return isUri;
|
||||||
|
}
|
||||||
|
|
||||||
public void setIsUri(boolean isUri) { this.isUri = isUri; }
|
public void setIsUri(boolean isUri) {
|
||||||
|
this.isUri = isUri;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setComposedSchemas(CodegenComposedSchemas composedSchemas) {
|
public void setComposedSchemas(CodegenComposedSchemas composedSchemas) {
|
||||||
@ -833,7 +841,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setIsBinary(boolean isBinary) {}
|
public void setIsBinary(boolean isBinary) {
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean getIsByteArray() {
|
public boolean getIsByteArray() {
|
||||||
@ -841,7 +850,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setIsByteArray(boolean isByteArray) {}
|
public void setIsByteArray(boolean isByteArray) {
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean getIsDecimal() {
|
public boolean getIsDecimal() {
|
||||||
@ -1005,7 +1015,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
sb.append(", parent='").append(parent).append('\'');
|
sb.append(", parent='").append(parent).append('\'');
|
||||||
sb.append(", parentSchema='").append(parentSchema).append('\'');
|
sb.append(", parentSchema='").append(parentSchema).append('\'');
|
||||||
sb.append(", interfaces=").append(interfaces);
|
sb.append(", interfaces=").append(interfaces);
|
||||||
sb.append(", interfaceModels=").append(interfaceModels !=null ? interfaceModels.size() : "[]");
|
sb.append(", interfaceModels=").append(interfaceModels != null ? interfaceModels.size() : "[]");
|
||||||
sb.append(", allParents=").append(allParents);
|
sb.append(", allParents=").append(allParents);
|
||||||
sb.append(", parentModel=").append(parentModel);
|
sb.append(", parentModel=").append(parentModel);
|
||||||
sb.append(", children=").append(children != null ? children.size() : "[]");
|
sb.append(", children=").append(children != null ? children.size() : "[]");
|
||||||
@ -1141,10 +1151,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; }
|
public Map<String, CodegenProperty> getRequiredVarsMap() {
|
||||||
|
return requiredVarsMap;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; }
|
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
|
||||||
|
this.requiredVarsMap = requiredVarsMap;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove duplicated properties in all variable list
|
* Remove duplicated properties in all variable list
|
||||||
|
@ -24,7 +24,8 @@ public final class CodegenModelFactory {
|
|||||||
public static <T> T newInstance(CodegenModelType type) {
|
public static <T> T newInstance(CodegenModelType type) {
|
||||||
try {
|
try {
|
||||||
return (T) type.getDefaultImplementation().getDeclaredConstructor().newInstance();
|
return (T) type.getDefaultImplementation().getDeclaredConstructor().newInstance();
|
||||||
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
|
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException |
|
||||||
|
InvocationTargetException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,8 @@ package org.openapitools.codegen;
|
|||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
@Getter public enum CodegenModelType {
|
@Getter
|
||||||
|
public enum CodegenModelType {
|
||||||
|
|
||||||
MODEL(CodegenModel.class),
|
MODEL(CodegenModel.class),
|
||||||
OPERATION(CodegenOperation.class),
|
OPERATION(CodegenOperation.class),
|
||||||
|
@ -220,7 +220,9 @@ public class CodegenOperation {
|
|||||||
*
|
*
|
||||||
* @return true if responses contain only 1 entry and it's a default response, false otherwise
|
* @return true if responses contain only 1 entry and it's a default response, false otherwise
|
||||||
*/
|
*/
|
||||||
public boolean getHasOnlyDefaultResponse() { return responses.size() == 1 && getHasDefaultResponse(); }
|
public boolean getHasOnlyDefaultResponse() {
|
||||||
|
return responses.size() == 1 && getHasDefaultResponse();
|
||||||
|
}
|
||||||
|
|
||||||
public boolean getAllResponsesAreErrors() {
|
public boolean getAllResponsesAreErrors() {
|
||||||
return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
|
return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
|
||||||
@ -237,7 +239,7 @@ public class CodegenOperation {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent();
|
LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent();
|
||||||
for (String contentType: content.keySet()) {
|
for (String contentType : content.keySet()) {
|
||||||
contentTypeToOperation.put(contentType, this);
|
contentTypeToOperation.put(contentType, this);
|
||||||
}
|
}
|
||||||
return contentTypeToOperation;
|
return contentTypeToOperation;
|
||||||
|
@ -17,17 +17,12 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen;
|
package org.openapitools.codegen;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
import io.swagger.v3.oas.models.examples.Example;
|
import io.swagger.v3.oas.models.examples.Example;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Describes a single operation parameter in the OAS specification.
|
* Describes a single operation parameter in the OAS specification.
|
||||||
* A unique parameter is defined by a combination of a name and location.
|
* A unique parameter is defined by a combination of a name and location.
|
||||||
@ -50,7 +45,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
|
|||||||
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
|
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
|
||||||
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
|
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
|
||||||
public boolean isArray, isMap;
|
public boolean isArray, isMap;
|
||||||
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
|
/**
|
||||||
|
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
|
||||||
|
*/
|
||||||
public boolean isOptional;
|
public boolean isOptional;
|
||||||
public boolean isFile;
|
public boolean isFile;
|
||||||
public boolean isEnum;
|
public boolean isEnum;
|
||||||
@ -291,7 +288,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
|
|||||||
items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation,
|
items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation,
|
||||||
getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(),
|
getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(),
|
||||||
getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(),
|
getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(),
|
||||||
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull,isVoid,
|
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, isVoid,
|
||||||
additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger,
|
additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger,
|
||||||
hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content,
|
hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content,
|
||||||
requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties,
|
requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties,
|
||||||
|
@ -20,12 +20,7 @@ package org.openapitools.codegen;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties {
|
public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties {
|
||||||
/**
|
/**
|
||||||
@ -178,7 +173,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
|
|||||||
public boolean isAnyType;
|
public boolean isAnyType;
|
||||||
public boolean isArray;
|
public boolean isArray;
|
||||||
public boolean isMap;
|
public boolean isMap;
|
||||||
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
|
/**
|
||||||
|
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
|
||||||
|
*/
|
||||||
public boolean isOptional;
|
public boolean isOptional;
|
||||||
public boolean isEnum; // true if the enum is defined inline
|
public boolean isEnum; // true if the enum is defined inline
|
||||||
public boolean isInnerEnum; // Enums declared inline will be located inside the generic model, changing how the enum is referenced in some cases.
|
public boolean isInnerEnum; // Enums declared inline will be located inside the generic model, changing how the enum is referenced in some cases.
|
||||||
@ -243,7 +240,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
|
|||||||
private boolean hasDiscriminatorWithNonEmptyMapping;
|
private boolean hasDiscriminatorWithNonEmptyMapping;
|
||||||
private CodegenComposedSchemas composedSchemas = null;
|
private CodegenComposedSchemas composedSchemas = null;
|
||||||
private boolean hasMultipleTypes = false;
|
private boolean hasMultipleTypes = false;
|
||||||
/** true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization */
|
/**
|
||||||
|
* true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization
|
||||||
|
*/
|
||||||
private boolean hasSanitizedName = false;
|
private boolean hasSanitizedName = false;
|
||||||
private Map<String, CodegenProperty> requiredVarsMap;
|
private Map<String, CodegenProperty> requiredVarsMap;
|
||||||
private String ref;
|
private String ref;
|
||||||
@ -849,7 +848,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
|
|||||||
return hasSanitizedName;
|
return hasSanitizedName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHasSanitizedName(boolean hasSanitizedName) { this.hasSanitizedName = hasSanitizedName; }
|
public void setHasSanitizedName(boolean hasSanitizedName) {
|
||||||
|
this.hasSanitizedName = hasSanitizedName;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean getIsUuid() {
|
public boolean getIsUuid() {
|
||||||
|
@ -63,7 +63,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
public boolean simpleType;
|
public boolean simpleType;
|
||||||
public boolean primitiveType;
|
public boolean primitiveType;
|
||||||
public boolean isMap;
|
public boolean isMap;
|
||||||
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
|
/**
|
||||||
|
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
|
||||||
|
*/
|
||||||
public boolean isOptional;
|
public boolean isOptional;
|
||||||
public boolean isArray;
|
public boolean isArray;
|
||||||
public boolean isBinary = false;
|
public boolean isBinary = false;
|
||||||
@ -212,7 +214,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
// use content.mediaType.schema.setContains instead of this
|
// use content.mediaType.schema.setContains instead of this
|
||||||
@Override
|
@Override
|
||||||
public void setContains(CodegenProperty contains) {}
|
public void setContains(CodegenProperty contains) {
|
||||||
|
}
|
||||||
|
|
||||||
// use content.mediaType.schema.getDependentRequired instead of this
|
// use content.mediaType.schema.getDependentRequired instead of this
|
||||||
@Override
|
@Override
|
||||||
@ -222,7 +225,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
// use content.mediaType.schema.setDependentRequired instead of this
|
// use content.mediaType.schema.setDependentRequired instead of this
|
||||||
@Override
|
@Override
|
||||||
public void setDependentRequired(LinkedHashMap<String, List<String>> dependentRequired) {}
|
public void setDependentRequired(LinkedHashMap<String, List<String>> dependentRequired) {
|
||||||
|
}
|
||||||
|
|
||||||
// use content.mediaType.schema.getIsBooleanSchemaTrue instead of this
|
// use content.mediaType.schema.getIsBooleanSchemaTrue instead of this
|
||||||
@Override
|
@Override
|
||||||
@ -232,7 +236,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
// use content.mediaType.schema.setIsBooleanSchemaTrue instead of this
|
// use content.mediaType.schema.setIsBooleanSchemaTrue instead of this
|
||||||
@Override
|
@Override
|
||||||
public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {}
|
public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {
|
||||||
|
}
|
||||||
|
|
||||||
// use content.mediaType.schema.getIsBooleanSchemaFalse instead of this
|
// use content.mediaType.schema.getIsBooleanSchemaFalse instead of this
|
||||||
@Override
|
@Override
|
||||||
@ -242,7 +247,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
// use content.mediaType.schema.setIsBooleanSchemaFalse instead of this
|
// use content.mediaType.schema.setIsBooleanSchemaFalse instead of this
|
||||||
@Override
|
@Override
|
||||||
public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {}
|
public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {
|
||||||
|
}
|
||||||
|
|
||||||
// use content.mediaType.schema.getFormat instead of this
|
// use content.mediaType.schema.getFormat instead of this
|
||||||
@Override
|
@Override
|
||||||
@ -252,7 +258,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
// use content.mediaType.schema.setFormat instead of this
|
// use content.mediaType.schema.setFormat instead of this
|
||||||
@Override
|
@Override
|
||||||
public void setFormat(String format) {}
|
public void setFormat(String format) {
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getPattern() {
|
public String getPattern() {
|
||||||
@ -782,16 +789,24 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; }
|
public Map<String, CodegenProperty> getRequiredVarsMap() {
|
||||||
|
return requiredVarsMap;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; }
|
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
|
||||||
|
this.requiredVarsMap = requiredVarsMap;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getRef() { return ref; }
|
public String getRef() {
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setRef(String ref) { this.ref=ref; }
|
public void setRef(String ref) {
|
||||||
|
this.ref = ref;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean getSchemaIsFromAdditionalProperties() {
|
public boolean getSchemaIsFromAdditionalProperties() {
|
||||||
@ -889,5 +904,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setIsEnum(boolean isEnum) {}
|
public void setIsEnum(boolean isEnum) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,11 +17,7 @@
|
|||||||
|
|
||||||
package org.openapitools.codegen;
|
package org.openapitools.codegen;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class CodegenSecurity {
|
public class CodegenSecurity {
|
||||||
@ -49,10 +45,10 @@ public class CodegenSecurity {
|
|||||||
// OpenId specific
|
// OpenId specific
|
||||||
public String openIdConnectUrl;
|
public String openIdConnectUrl;
|
||||||
|
|
||||||
public CodegenSecurity () {
|
public CodegenSecurity() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public CodegenSecurity (CodegenSecurity original) {
|
public CodegenSecurity(CodegenSecurity original) {
|
||||||
this.name = original.name;
|
this.name = original.name;
|
||||||
this.description = original.description;
|
this.description = original.description;
|
||||||
this.type = original.type;
|
this.type = original.type;
|
||||||
@ -97,8 +93,8 @@ public class CodegenSecurity {
|
|||||||
// In such cases, no filtering is performed.
|
// In such cases, no filtering is performed.
|
||||||
if (!(Boolean.TRUE.equals(isOAuth) || Boolean.TRUE.equals(isOpenId))) {
|
if (!(Boolean.TRUE.equals(isOAuth) || Boolean.TRUE.equals(isOpenId))) {
|
||||||
filteredSecurity.scopes = filterScopes.stream()
|
filteredSecurity.scopes = filterScopes.stream()
|
||||||
.map(s -> new HashMap<String, Object>(Map.of("scope", s)))
|
.map(s -> new HashMap<String, Object>(Map.of("scope", s)))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
return filteredSecurity;
|
return filteredSecurity;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -70,10 +70,10 @@ import org.openapitools.codegen.utils.OneOfImplementorAdditionalData;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.InputStreamReader;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
@ -350,7 +350,6 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
* first from additionalProperties
|
* first from additionalProperties
|
||||||
* then from the getter in this instance
|
* then from the getter in this instance
|
||||||
* then from the fields in this instance
|
* then from the fields in this instance
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
protected void useCodegenAsMustacheParentContext() {
|
protected void useCodegenAsMustacheParentContext() {
|
||||||
additionalProperties.put(CodegenConstants.MUSTACHE_PARENT_CONTEXT, this);
|
additionalProperties.put(CodegenConstants.MUSTACHE_PARENT_CONTEXT, this);
|
||||||
@ -392,7 +391,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
convertPropertyToBooleanAndWriteBack(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, this::setDisallowAdditionalPropertiesIfNotPresent);
|
convertPropertyToBooleanAndWriteBack(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, this::setDisallowAdditionalPropertiesIfNotPresent);
|
||||||
convertPropertyToBooleanAndWriteBack(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, this::setEnumUnknownDefaultCase);
|
convertPropertyToBooleanAndWriteBack(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, this::setEnumUnknownDefaultCase);
|
||||||
convertPropertyToBooleanAndWriteBack(CodegenConstants.AUTOSET_CONSTANTS, this::setAutosetConstants);
|
convertPropertyToBooleanAndWriteBack(CodegenConstants.AUTOSET_CONSTANTS, this::setAutosetConstants);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/***
|
/***
|
||||||
@ -546,6 +545,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
* This usually occurs when the data type is different.
|
* This usually occurs when the data type is different.
|
||||||
* We can also consider discriminators as new because the derived class discriminator will have to be defined again
|
* We can also consider discriminators as new because the derived class discriminator will have to be defined again
|
||||||
* to contain a new value. Doing so prevents having to include the discriminator in the constructor.
|
* to contain a new value. Doing so prevents having to include the discriminator in the constructor.
|
||||||
|
*
|
||||||
* @param model
|
* @param model
|
||||||
* @param property
|
* @param property
|
||||||
* @return
|
* @return
|
||||||
@ -553,9 +553,9 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
private boolean codegenPropertyIsNew(CodegenModel model, CodegenProperty property) {
|
private boolean codegenPropertyIsNew(CodegenModel model, CodegenProperty property) {
|
||||||
return model.parentModel == null
|
return model.parentModel == null
|
||||||
? false
|
? false
|
||||||
: model.parentModel.allVars.stream().anyMatch(p ->
|
: model.parentModel.allVars.stream().anyMatch(p ->
|
||||||
p.name.equals(property.name) &&
|
p.name.equals(property.name) &&
|
||||||
(p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false));
|
(p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -874,8 +874,8 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
/**
|
/**
|
||||||
* Return the enum default value in the language specified format
|
* Return the enum default value in the language specified format
|
||||||
*
|
*
|
||||||
* @param property The codegen property to create the default for.
|
* @param property The codegen property to create the default for.
|
||||||
* @param value Enum variable name
|
* @param value Enum variable name
|
||||||
* @return the default value for the enum
|
* @return the default value for the enum
|
||||||
*/
|
*/
|
||||||
public String toEnumDefaultValue(CodegenProperty property, String value) {
|
public String toEnumDefaultValue(CodegenProperty property, String value) {
|
||||||
@ -1133,6 +1133,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* This method escapes text to be used in a single quoted string
|
* This method escapes text to be used in a single quoted string
|
||||||
|
*
|
||||||
* @param input the input string
|
* @param input the input string
|
||||||
* @return the escaped string
|
* @return the escaped string
|
||||||
*/
|
*/
|
||||||
@ -3275,7 +3276,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) {
|
if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) {
|
||||||
Schema discSchema = ModelUtils.getReferencedSchema(openAPI, (Schema)refSchema.getProperties().get(discPropName));
|
Schema discSchema = ModelUtils.getReferencedSchema(openAPI, (Schema) refSchema.getProperties().get(discPropName));
|
||||||
CodegenProperty cp = new CodegenProperty();
|
CodegenProperty cp = new CodegenProperty();
|
||||||
if (ModelUtils.isStringSchema(discSchema)) {
|
if (ModelUtils.isStringSchema(discSchema)) {
|
||||||
cp.isString = true;
|
cp.isString = true;
|
||||||
@ -6904,7 +6905,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
* writes it back to additionalProperties to be usable as a boolean in
|
* writes it back to additionalProperties to be usable as a boolean in
|
||||||
* mustache files.
|
* mustache files.
|
||||||
*
|
*
|
||||||
* @param propertyKey property key
|
* @param propertyKey property key
|
||||||
* @param booleanSetter the setter function reference
|
* @param booleanSetter the setter function reference
|
||||||
* @return property value as boolean or false if it does not exist
|
* @return property value as boolean or false if it does not exist
|
||||||
*/
|
*/
|
||||||
@ -6923,7 +6924,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
* writes it back to additionalProperties to be usable as a string in
|
* writes it back to additionalProperties to be usable as a string in
|
||||||
* mustache files.
|
* mustache files.
|
||||||
*
|
*
|
||||||
* @param propertyKey property key
|
* @param propertyKey property key
|
||||||
* @param stringSetter the setter function reference
|
* @param stringSetter the setter function reference
|
||||||
* @return property value as String or null if not found
|
* @return property value as String or null if not found
|
||||||
*/
|
*/
|
||||||
@ -6936,7 +6937,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
* writes it back to additionalProperties to be usable as T in
|
* writes it back to additionalProperties to be usable as T in
|
||||||
* mustache files.
|
* mustache files.
|
||||||
*
|
*
|
||||||
* @param propertyKey property key
|
* @param propertyKey property key
|
||||||
* @param genericTypeSetter the setter function reference
|
* @param genericTypeSetter the setter function reference
|
||||||
* @return property value as instance of type T or null if not found
|
* @return property value as instance of type T or null if not found
|
||||||
*/
|
*/
|
||||||
@ -8237,7 +8238,7 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
int exitValue = p.exitValue();
|
int exitValue = p.exitValue();
|
||||||
if (exitValue != 0) {
|
if (exitValue != 0) {
|
||||||
try (InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8);
|
try (InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8);
|
||||||
BufferedReader br = new BufferedReader(inputStreamReader)) {
|
BufferedReader br = new BufferedReader(inputStreamReader)) {
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
String line;
|
String line;
|
||||||
while ((line = br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
@ -8391,7 +8392,8 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
|
|
||||||
public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
|
public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
|
||||||
}
|
}
|
||||||
//// End of methods related to the "useOneOfInterfaces" feature
|
|
||||||
|
/// / End of methods related to the "useOneOfInterfaces" feature
|
||||||
|
|
||||||
protected void modifyFeatureSet(Consumer<FeatureSet.Builder> processor) {
|
protected void modifyFeatureSet(Consumer<FeatureSet.Builder> processor) {
|
||||||
FeatureSet.Builder builder = getFeatureSet().modify();
|
FeatureSet.Builder builder = getFeatureSet().modify();
|
||||||
@ -8403,7 +8405,8 @@ public class DefaultCodegen implements CodegenConfig {
|
|||||||
/**
|
/**
|
||||||
* An map entry for cached sanitized names.
|
* An map entry for cached sanitized names.
|
||||||
*/
|
*/
|
||||||
@Getter private static class SanitizeNameOptions {
|
@Getter
|
||||||
|
private static class SanitizeNameOptions {
|
||||||
public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
|
public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.removeCharRegEx = removeCharRegEx;
|
this.removeCharRegEx = removeCharRegEx;
|
||||||
|
@ -18,11 +18,7 @@
|
|||||||
package org.openapitools.codegen;
|
package org.openapitools.codegen;
|
||||||
|
|
||||||
import io.swagger.v3.core.util.Json;
|
import io.swagger.v3.core.util.Json;
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.*;
|
||||||
import io.swagger.v3.oas.models.Operation;
|
|
||||||
import io.swagger.v3.oas.models.PathItem;
|
|
||||||
import io.swagger.v3.oas.models.Paths;
|
|
||||||
import io.swagger.v3.oas.models.SpecVersion;
|
|
||||||
import io.swagger.v3.oas.models.info.Contact;
|
import io.swagger.v3.oas.models.info.Contact;
|
||||||
import io.swagger.v3.oas.models.info.Info;
|
import io.swagger.v3.oas.models.info.Info;
|
||||||
import io.swagger.v3.oas.models.info.License;
|
import io.swagger.v3.oas.models.info.License;
|
||||||
@ -35,12 +31,8 @@ import org.apache.commons.io.FilenameUtils;
|
|||||||
import org.apache.commons.io.IOCase;
|
import org.apache.commons.io.IOCase;
|
||||||
import org.apache.commons.lang3.ObjectUtils;
|
import org.apache.commons.lang3.ObjectUtils;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.openapitools.codegen.api.TemplateDefinition;
|
import org.openapitools.codegen.api.*;
|
||||||
import org.openapitools.codegen.api.TemplatePathLocator;
|
|
||||||
import org.openapitools.codegen.api.TemplateProcessor;
|
|
||||||
import org.openapitools.codegen.config.GlobalSettings;
|
import org.openapitools.codegen.config.GlobalSettings;
|
||||||
import org.openapitools.codegen.api.TemplatingEngineAdapter;
|
|
||||||
import org.openapitools.codegen.api.TemplateFileType;
|
|
||||||
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
|
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
|
||||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||||
import org.openapitools.codegen.meta.Stability;
|
import org.openapitools.codegen.meta.Stability;
|
||||||
@ -50,15 +42,13 @@ import org.openapitools.codegen.templating.CommonTemplateContentLocator;
|
|||||||
import org.openapitools.codegen.templating.GeneratorTemplateContentLocator;
|
import org.openapitools.codegen.templating.GeneratorTemplateContentLocator;
|
||||||
import org.openapitools.codegen.templating.MustacheEngineAdapter;
|
import org.openapitools.codegen.templating.MustacheEngineAdapter;
|
||||||
import org.openapitools.codegen.templating.TemplateManagerOptions;
|
import org.openapitools.codegen.templating.TemplateManagerOptions;
|
||||||
import org.openapitools.codegen.utils.ImplementationVersion;
|
import org.openapitools.codegen.utils.*;
|
||||||
import org.openapitools.codegen.utils.ModelUtils;
|
|
||||||
import org.openapitools.codegen.utils.ProcessUtils;
|
|
||||||
import org.openapitools.codegen.utils.URLPathUtils;
|
|
||||||
import org.openapitools.codegen.utils.SemVer;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@ -97,8 +87,8 @@ public class DefaultGenerator implements Generator {
|
|||||||
private String contextPath;
|
private String contextPath;
|
||||||
private Map<String, String> generatorPropertyDefaults = new HashMap<>();
|
private Map<String, String> generatorPropertyDefaults = new HashMap<>();
|
||||||
/**
|
/**
|
||||||
* Retrieves an instance to the configured template processor, available after user-defined options are
|
* Retrieves an instance to the configured template processor, available after user-defined options are
|
||||||
* applied via
|
* applied via
|
||||||
*/
|
*/
|
||||||
@Getter protected TemplateProcessor templateProcessor = null;
|
@Getter protected TemplateProcessor templateProcessor = null;
|
||||||
|
|
||||||
@ -461,7 +451,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Set<String> modelKeys = modelKeysSupplier.get();
|
Set<String> modelKeys = modelKeysSupplier.get();
|
||||||
if(modelKeys.isEmpty()) {
|
if (modelKeys.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -536,11 +526,11 @@ public class DefaultGenerator implements Generator {
|
|||||||
allProcessedModels = config.postProcessAllModels(allProcessedModels);
|
allProcessedModels = config.postProcessAllModels(allProcessedModels);
|
||||||
|
|
||||||
if (generateRecursiveDependentModels) {
|
if (generateRecursiveDependentModels) {
|
||||||
for(ModelsMap modelsMap : allProcessedModels.values()) {
|
for (ModelsMap modelsMap : allProcessedModels.values()) {
|
||||||
for(ModelMap mm: modelsMap.getModels()) {
|
for (ModelMap mm : modelsMap.getModels()) {
|
||||||
CodegenModel cm = mm.getModel();
|
CodegenModel cm = mm.getModel();
|
||||||
if (cm != null) {
|
if (cm != null) {
|
||||||
for(CodegenProperty variable : cm.getVars()) {
|
for (CodegenProperty variable : cm.getVars()) {
|
||||||
generateModelsForVariable(files, allModels, unusedModels, aliasModels, processedModels, variable);
|
generateModelsForVariable(files, allModels, unusedModels, aliasModels, processedModels, variable);
|
||||||
}
|
}
|
||||||
//TODO: handle interfaces
|
//TODO: handle interfaces
|
||||||
@ -552,7 +542,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generate files based on processed models
|
// generate files based on processed models
|
||||||
for (String modelName : allProcessedModels.keySet()) {
|
for (String modelName : allProcessedModels.keySet()) {
|
||||||
ModelsMap models = allProcessedModels.get(modelName);
|
ModelsMap models = allProcessedModels.get(modelName);
|
||||||
@ -616,10 +606,10 @@ public class DefaultGenerator implements Generator {
|
|||||||
if (!processedModels.contains(key) && allSchemas.containsKey(key)) {
|
if (!processedModels.contains(key) && allSchemas.containsKey(key)) {
|
||||||
generateModels(files, allModels, unusedModels, aliasModels, processedModels, () -> Set.of(key));
|
generateModels(files, allModels, unusedModels, aliasModels, processedModels, () -> Set.of(key));
|
||||||
} else {
|
} else {
|
||||||
LOGGER.info("Type " + variable.getComplexType()+" of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
|
LOGGER.info("Type " + variable.getComplexType() + " of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
LOGGER.info("Type " + variable.getOpenApiType()+" of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
|
LOGGER.info("Type " + variable.getOpenApiType() + " of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -627,7 +617,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
Map<String, Schema> schemaMap = ModelUtils.getSchemas(this.openAPI);
|
Map<String, Schema> schemaMap = ModelUtils.getSchemas(this.openAPI);
|
||||||
Set<String> keys = schemaMap.keySet();
|
Set<String> keys = schemaMap.keySet();
|
||||||
String simpleRef;
|
String simpleRef;
|
||||||
if(keys.contains(type)) {
|
if (keys.contains(type)) {
|
||||||
return type;
|
return type;
|
||||||
} else if (keys.contains(simpleRef = ModelUtils.getSimpleRef(ref))) {
|
} else if (keys.contains(simpleRef = ModelUtils.getSimpleRef(ref))) {
|
||||||
return simpleRef;
|
return simpleRef;
|
||||||
@ -688,7 +678,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
for (String tag : paths.keySet()) {
|
for (String tag : paths.keySet()) {
|
||||||
try {
|
try {
|
||||||
List<CodegenOperation> ops = paths.get(tag);
|
List<CodegenOperation> ops = paths.get(tag);
|
||||||
if(!this.config.isSkipSortingOperations()) {
|
if (!this.config.isSkipSortingOperations()) {
|
||||||
// sort operations by operationId
|
// sort operations by operationId
|
||||||
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId));
|
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId));
|
||||||
}
|
}
|
||||||
@ -931,17 +921,17 @@ public class DefaultGenerator implements Generator {
|
|||||||
String outputDir = config.getOutputDir() + File.separator + config.templateOutputDirs().get(templateName);
|
String outputDir = config.getOutputDir() + File.separator + config.templateOutputDirs().get(templateName);
|
||||||
String filename = config.apiFilename(templateName, tag, outputDir);
|
String filename = config.apiFilename(templateName, tag, outputDir);
|
||||||
// do not overwrite apiController file for spring server
|
// do not overwrite apiController file for spring server
|
||||||
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){
|
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)) {
|
||||||
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS, outputDir);
|
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS, outputDir);
|
||||||
} else {
|
} else {
|
||||||
LOGGER.info("Implementation file {} is not overwritten",filename);
|
LOGGER.info("Implementation file {} is not overwritten", filename);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
String filename = config.apiFilename(templateName, tag);
|
String filename = config.apiFilename(templateName, tag);
|
||||||
if(apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){
|
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)) {
|
||||||
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS);
|
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS);
|
||||||
} else {
|
} else {
|
||||||
LOGGER.info("Implementation file {} is not overwritten",filename);
|
LOGGER.info("Implementation file {} is not overwritten", filename);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (written != null) {
|
if (written != null) {
|
||||||
@ -1218,9 +1208,9 @@ public class DefaultGenerator implements Generator {
|
|||||||
* <p>
|
* <p>
|
||||||
* Examples:
|
* Examples:
|
||||||
* <p>
|
* <p>
|
||||||
* boolean hasOAuthMethods
|
* boolean hasOAuthMethods
|
||||||
* <p>
|
* <p>
|
||||||
* List<CodegenSecurity> oauthMethods
|
* List<CodegenSecurity> oauthMethods
|
||||||
*
|
*
|
||||||
* @param bundle the map which the booleans and collections will be added
|
* @param bundle the map which the booleans and collections will be added
|
||||||
*/
|
*/
|
||||||
@ -1490,7 +1480,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
return ops;
|
return ops;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, List<CodegenOperation>> processWebhooks(Map<String, PathItem> webhooks) {
|
public Map<String, List<CodegenOperation>> processWebhooks(Map<String, PathItem> webhooks) {
|
||||||
Map<String, List<CodegenOperation>> ops = new TreeMap<>();
|
Map<String, List<CodegenOperation>> ops = new TreeMap<>();
|
||||||
// when input file is not valid and doesn't contain any paths
|
// when input file is not valid and doesn't contain any paths
|
||||||
if (webhooks == null) {
|
if (webhooks == null) {
|
||||||
@ -1619,7 +1609,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static String generateParameterId(Parameter parameter) {
|
private static String generateParameterId(Parameter parameter) {
|
||||||
return null == parameter.get$ref() ? parameter.getName() + ":" + parameter.getIn() : parameter.get$ref() ;
|
return null == parameter.get$ref() ? parameter.getName() + ":" + parameter.getIn() : parameter.get$ref();
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationsMap processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops, List<ModelMap> allModels) {
|
private OperationsMap processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops, List<ModelMap> allModels) {
|
||||||
@ -2013,7 +2003,7 @@ public class DefaultGenerator implements Generator {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Collections.sort(relativePaths, (a, b) -> IOCase.SENSITIVE.checkCompareTo(a,b));
|
Collections.sort(relativePaths, (a, b) -> IOCase.SENSITIVE.checkCompareTo(a, b));
|
||||||
relativePaths.forEach(relativePath -> {
|
relativePaths.forEach(relativePath -> {
|
||||||
sb.append(relativePath).append(System.lineSeparator());
|
sb.append(relativePath).append(System.lineSeparator());
|
||||||
});
|
});
|
||||||
|
@ -9,25 +9,26 @@ import java.util.Locale;
|
|||||||
/**
|
/**
|
||||||
* Holds details about a file's write status for display via the --dry-run option of CLI
|
* Holds details about a file's write status for display via the --dry-run option of CLI
|
||||||
*/
|
*/
|
||||||
@Getter class DryRunStatus {
|
@Getter
|
||||||
|
class DryRunStatus {
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets the target path of the file write operation
|
* Gets the target path of the file write operation
|
||||||
*
|
*
|
||||||
* @return a {@link Path} instance
|
* @return a {@link Path} instance
|
||||||
*/
|
*/
|
||||||
private final Path path;
|
private final Path path;
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets the
|
* Gets the
|
||||||
* as determined by the generator's workflow
|
* as determined by the generator's workflow
|
||||||
*
|
*
|
||||||
* @return A {@link State} enum detailing the expected operation of the generator's workflow
|
* @return A {@link State} enum detailing the expected operation of the generator's workflow
|
||||||
*/
|
*/
|
||||||
private State state;
|
private State state;
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets the reason for the file's
|
* Gets the reason for the file's
|
||||||
*
|
*
|
||||||
* @return A human-readable string which explains why this file's dry-run resulted in the defined {@link State}
|
* @return A human-readable string which explains why this file's dry-run resulted in the defined {@link State}
|
||||||
*/
|
*/
|
||||||
@ -110,7 +111,8 @@ import java.util.Locale;
|
|||||||
/**
|
/**
|
||||||
* Represents the possible states of a file write operation as determined by the Generator
|
* Represents the possible states of a file write operation as determined by the Generator
|
||||||
*/
|
*/
|
||||||
@Getter enum State {
|
@Getter
|
||||||
|
enum State {
|
||||||
Write("w", "Write"),
|
Write("w", "Write"),
|
||||||
WriteIfNewer("n", "Write if New/Updated"),
|
WriteIfNewer("n", "Write if New/Updated"),
|
||||||
Ignored("i", "Ignored"),
|
Ignored("i", "Ignored"),
|
||||||
@ -120,14 +122,14 @@ import java.util.Locale;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets the short value used for display
|
* Gets the short value used for display
|
||||||
*
|
*
|
||||||
* @return A character representing this state
|
* @return A character representing this state
|
||||||
*/
|
*/
|
||||||
private final String shortDisplay;
|
private final String shortDisplay;
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets a description of the state which is more human-readable than the enum's name
|
* Gets a description of the state which is more human-readable than the enum's name
|
||||||
*
|
*
|
||||||
* @return A human-readable description
|
* @return A human-readable description
|
||||||
*/
|
*/
|
||||||
|
@ -18,7 +18,7 @@ import java.util.Map;
|
|||||||
public class DryRunTemplateManager implements TemplateProcessor {
|
public class DryRunTemplateManager implements TemplateProcessor {
|
||||||
private final TemplateManagerOptions options;
|
private final TemplateManagerOptions options;
|
||||||
private final Map<String, DryRunStatus> dryRunStatusMap = new HashMap<>();
|
private final Map<String, DryRunStatus> dryRunStatusMap = new HashMap<>();
|
||||||
|
|
||||||
private final Map<String, Map<String, Object>> capturedTemplateData = new HashMap<>();
|
private final Map<String, Map<String, Object>> capturedTemplateData = new HashMap<>();
|
||||||
private boolean recordTemplateData = false;
|
private boolean recordTemplateData = false;
|
||||||
|
|
||||||
@ -65,9 +65,9 @@ public class DryRunTemplateManager implements TemplateProcessor {
|
|||||||
if (outputFile.exists()) {
|
if (outputFile.exists()) {
|
||||||
if (this.options.isSkipOverwrite()) {
|
if (this.options.isSkipOverwrite()) {
|
||||||
status = new DryRunStatus(
|
status = new DryRunStatus(
|
||||||
path,
|
path,
|
||||||
DryRunStatus.State.SkippedOverwrite,
|
DryRunStatus.State.SkippedOverwrite,
|
||||||
"File exists and skip overwrite option is enabled."
|
"File exists and skip overwrite option is enabled."
|
||||||
);
|
);
|
||||||
} else if (this.options.isMinimalUpdate()) {
|
} else if (this.options.isMinimalUpdate()) {
|
||||||
status.setState(DryRunStatus.State.WriteIfNewer);
|
status.setState(DryRunStatus.State.WriteIfNewer);
|
||||||
@ -118,10 +118,11 @@ public class DryRunTemplateManager implements TemplateProcessor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the captured template data for a specific file. Capturing must have
|
* Retrieve the captured template data for a specific file. Capturing must have
|
||||||
* been enabled via {@link #enableTemplateDataCapturing()} prior to generation.<br>
|
* been enabled via {@link #enableTemplateDataCapturing()} prior to generation.<br>
|
||||||
* Note: Not all files have template data (e.g. Metadata files) – in such case an empty
|
* Note: Not all files have template data (e.g. Metadata files) – in such case an empty
|
||||||
* map is returned.
|
* map is returned.
|
||||||
|
*
|
||||||
* @param generatedFile An absolute path to the generated file
|
* @param generatedFile An absolute path to the generated file
|
||||||
* @return Typically one of the *Map types found in {@link org.openapitools.codegen.model}
|
* @return Typically one of the *Map types found in {@link org.openapitools.codegen.model}
|
||||||
*/
|
*/
|
||||||
|
@ -1,20 +1,13 @@
|
|||||||
package org.openapitools.codegen;
|
package org.openapitools.codegen;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import java.util.Collections;
|
import io.swagger.v3.oas.models.media.Schema;
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import org.openapitools.codegen.meta.FeatureSet;
|
import org.openapitools.codegen.meta.FeatureSet;
|
||||||
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
|
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
|
||||||
import org.openapitools.codegen.utils.ModelUtils;
|
import org.openapitools.codegen.utils.ModelUtils;
|
||||||
|
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import java.util.*;
|
||||||
import io.swagger.v3.oas.models.media.Schema;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public interface IJsonSchemaValidationProperties {
|
public interface IJsonSchemaValidationProperties {
|
||||||
CodegenProperty getContains();
|
CodegenProperty getContains();
|
||||||
@ -108,14 +101,15 @@ public interface IJsonSchemaValidationProperties {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Tells if the datatype is a generic inner parameter of a <code>std::optional</code> for C++, or <code>Optional</code> (Java)<br>
|
* Tells if the datatype is a generic inner parameter of a <code>std::optional</code> for C++, or <code>Optional</code> (Java)<br>
|
||||||
* to resolve cases (detected in issue #6726) where :<br>
|
* to resolve cases (detected in issue #6726) where :<br>
|
||||||
* - <code>categoryOneOf</code> is a parameter of class <code>GetAccountVideos_categoryOneOf_parameter</code>, a model parameter that correctly prefixed by its namespace: <code>org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter</code><br>
|
* - <code>categoryOneOf</code> is a parameter of class <code>GetAccountVideos_categoryOneOf_parameter</code>, a model parameter that correctly prefixed by its namespace: <code>org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter</code><br>
|
||||||
* - but that <code>GetAccountVideos_categoryOneOf_parameter</code> class is inside an <code>std::optional</code><br>
|
* - but that <code>GetAccountVideos_categoryOneOf_parameter</code> class is inside an <code>std::optional</code><br>
|
||||||
* <br>
|
* <br>
|
||||||
* Then a correct generation of that parameter can be (for C++) <code>const std::optional<org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter> &categoryOneOf</code><br>
|
* Then a correct generation of that parameter can be (for C++) <code>const std::optional<org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter> &categoryOneOf</code><br>
|
||||||
* but using #isModel alone without #isOptional in mustache might produce <code>const org::openapitools::server::model::std::optional<org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter> &categoryOneOf</code> instead, that do not compile.
|
* but using #isModel alone without #isOptional in mustache might produce <code>const org::openapitools::server::model::std::optional<org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter> &categoryOneOf</code> instead, that do not compile.
|
||||||
*/
|
*/
|
||||||
boolean getIsOptional();
|
boolean getIsOptional();
|
||||||
|
|
||||||
void setIsOptional(boolean isOptional);
|
void setIsOptional(boolean isOptional);
|
||||||
|
|
||||||
boolean getIsArray();
|
boolean getIsArray();
|
||||||
|
@ -22,8 +22,6 @@ import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
|
|||||||
import com.fasterxml.jackson.databind.MapperFeature;
|
import com.fasterxml.jackson.databind.MapperFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import io.swagger.v3.core.util.Json;
|
import io.swagger.v3.core.util.Json;
|
||||||
import io.swagger.v3.oas.annotations.Webhook;
|
|
||||||
import io.swagger.v3.oas.annotations.Webhooks;
|
|
||||||
import io.swagger.v3.oas.models.*;
|
import io.swagger.v3.oas.models.*;
|
||||||
import io.swagger.v3.oas.models.PathItem.HttpMethod;
|
import io.swagger.v3.oas.models.PathItem.HttpMethod;
|
||||||
import io.swagger.v3.oas.models.callbacks.Callback;
|
import io.swagger.v3.oas.models.callbacks.Callback;
|
||||||
@ -37,7 +35,6 @@ import org.openapitools.codegen.utils.ModelUtils;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
public class InlineModelResolver {
|
public class InlineModelResolver {
|
||||||
@ -118,7 +115,7 @@ public class InlineModelResolver {
|
|||||||
* Flatten inline models in Webhooks
|
* Flatten inline models in Webhooks
|
||||||
*/
|
*/
|
||||||
private void flattenWebhooks() {
|
private void flattenWebhooks() {
|
||||||
Map<String, PathItem> webhooks = openAPI.getWebhooks();
|
Map<String, PathItem> webhooks = openAPI.getWebhooks();
|
||||||
if (webhooks == null) {
|
if (webhooks == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -536,8 +533,8 @@ public class InlineModelResolver {
|
|||||||
/**
|
/**
|
||||||
* Flatten inline models in parameters
|
* Flatten inline models in parameters
|
||||||
*
|
*
|
||||||
* @param modelName model name
|
* @param modelName model name
|
||||||
* @param parameters list of parameters
|
* @param parameters list of parameters
|
||||||
* @param operationId operation Id (optional)
|
* @param operationId operation Id (optional)
|
||||||
*/
|
*/
|
||||||
private void flattenParameters(String modelName, List<Parameter> parameters, String operationId) {
|
private void flattenParameters(String modelName, List<Parameter> parameters, String operationId) {
|
||||||
@ -619,18 +616,18 @@ public class InlineModelResolver {
|
|||||||
* allOf:
|
* allOf:
|
||||||
* - $ref: '#/components/schemas/Animal'
|
* - $ref: '#/components/schemas/Animal'
|
||||||
* - type: object
|
* - type: object
|
||||||
* properties:
|
* properties:
|
||||||
* name:
|
* name:
|
||||||
* type: string
|
* type: string
|
||||||
* age:
|
* age:
|
||||||
* type: string
|
* type: string
|
||||||
* - type: object
|
* - type: object
|
||||||
* properties:
|
* properties:
|
||||||
* breed:
|
* breed:
|
||||||
* type: string
|
* type: string
|
||||||
*
|
*
|
||||||
* @param key a unique name for the composed schema.
|
* @param key a unique name for the composed schema.
|
||||||
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
|
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
|
||||||
* @param skipAllOfInlineSchemas true if allOf inline schemas need to be skipped.
|
* @param skipAllOfInlineSchemas true if allOf inline schemas need to be skipped.
|
||||||
*/
|
*/
|
||||||
private void flattenComposedChildren(String key, List<Schema> children, boolean skipAllOfInlineSchemas) {
|
private void flattenComposedChildren(String key, List<Schema> children, boolean skipAllOfInlineSchemas) {
|
||||||
|
@ -20,23 +20,24 @@ public class ObjectWithTypeBooleans {
|
|||||||
* Other booleans: isUnboundedInteger/isNumber/isString/isMap/isArray/isBoolean/isNull
|
* Other booleans: isUnboundedInteger/isNumber/isString/isMap/isArray/isBoolean/isNull
|
||||||
* allow generator templates to decide how to render each payload into code
|
* allow generator templates to decide how to render each payload into code
|
||||||
* based upon what type it is. The booleans isX describe the value in value.
|
* based upon what type it is. The booleans isX describe the value in value.
|
||||||
|
*
|
||||||
* @param value the input payload that is stored
|
* @param value the input payload that is stored
|
||||||
*/
|
*/
|
||||||
public ObjectWithTypeBooleans(Object value) {
|
public ObjectWithTypeBooleans(Object value) {
|
||||||
Object usedValue = null;
|
Object usedValue = null;
|
||||||
if (value instanceof Integer){
|
if (value instanceof Integer) {
|
||||||
this.isUnboundedInteger = true;
|
this.isUnboundedInteger = true;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
} else if (value instanceof Double || value instanceof Float){
|
} else if (value instanceof Double || value instanceof Float) {
|
||||||
this.isNumber = true;
|
this.isNumber = true;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
} else if (value instanceof String) {
|
} else if (value instanceof String) {
|
||||||
this.isString = true;
|
this.isString = true;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
} else if (value instanceof LinkedHashMap) {
|
} else if (value instanceof LinkedHashMap) {
|
||||||
LinkedHashMap<String, Object> castValue = (LinkedHashMap<String, Object>) value;
|
LinkedHashMap<String, Object> castValue = (LinkedHashMap<String, Object>) value;
|
||||||
LinkedHashMap<ObjectWithTypeBooleans, ObjectWithTypeBooleans> castMap = new LinkedHashMap<>();
|
LinkedHashMap<ObjectWithTypeBooleans, ObjectWithTypeBooleans> castMap = new LinkedHashMap<>();
|
||||||
for (Map.Entry entry: castValue.entrySet()) {
|
for (Map.Entry entry : castValue.entrySet()) {
|
||||||
ObjectWithTypeBooleans entryKey = new ObjectWithTypeBooleans(entry.getKey());
|
ObjectWithTypeBooleans entryKey = new ObjectWithTypeBooleans(entry.getKey());
|
||||||
ObjectWithTypeBooleans entryValue = new ObjectWithTypeBooleans(entry.getValue());
|
ObjectWithTypeBooleans entryValue = new ObjectWithTypeBooleans(entry.getValue());
|
||||||
castMap.put(entryKey, entryValue);
|
castMap.put(entryKey, entryValue);
|
||||||
@ -45,7 +46,7 @@ public class ObjectWithTypeBooleans {
|
|||||||
this.isMap = true;
|
this.isMap = true;
|
||||||
} else if (value instanceof ArrayList) {
|
} else if (value instanceof ArrayList) {
|
||||||
ArrayList<ObjectWithTypeBooleans> castList = new ArrayList<>();
|
ArrayList<ObjectWithTypeBooleans> castList = new ArrayList<>();
|
||||||
for (Object item: (ArrayList<Object>) value) {
|
for (Object item : (ArrayList<Object>) value) {
|
||||||
castList.add(new ObjectWithTypeBooleans(item));
|
castList.add(new ObjectWithTypeBooleans(item));
|
||||||
}
|
}
|
||||||
this.value = castList;
|
this.value = castList;
|
||||||
|
@ -35,7 +35,6 @@ import java.util.*;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.openapitools.codegen.utils.StringUtils.getUniqueString;
|
import static org.openapitools.codegen.utils.StringUtils.getUniqueString;
|
||||||
import static org.openapitools.codegen.utils.StringUtils.underscore;
|
|
||||||
|
|
||||||
public class OpenAPINormalizer {
|
public class OpenAPINormalizer {
|
||||||
private OpenAPI openAPI;
|
private OpenAPI openAPI;
|
||||||
@ -546,7 +545,7 @@ public class OpenAPINormalizer {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Map.Entry<String, ApiResponse> entry : apiResponses.entrySet()) {
|
for (Map.Entry<String, ApiResponse> entry : apiResponses.entrySet()) {
|
||||||
normalizeResponse(entry.getValue());
|
normalizeResponse(entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1013,7 +1012,6 @@ public class OpenAPINormalizer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to
|
* If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to
|
||||||
* ensure inter-dependency between properties. It's a workaround as such validation is not supported at the moment.
|
* ensure inter-dependency between properties. It's a workaround as such validation is not supported at the moment.
|
||||||
|
@ -6,7 +6,8 @@ import lombok.Setter;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter
|
||||||
|
@Setter
|
||||||
public class SpecValidationException extends RuntimeException {
|
public class SpecValidationException extends RuntimeException {
|
||||||
|
|
||||||
private Set<String> errors;
|
private Set<String> errors;
|
||||||
@ -100,8 +101,8 @@ public class SpecValidationException extends RuntimeException {
|
|||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.append(System.lineSeparator())
|
sb.append(System.lineSeparator())
|
||||||
.append("Errors: ")
|
.append("Errors: ")
|
||||||
.append(System.lineSeparator());
|
.append(System.lineSeparator());
|
||||||
|
|
||||||
Optional.ofNullable(errors).ifPresent(_errors -> {
|
Optional.ofNullable(errors).ifPresent(_errors -> {
|
||||||
for (String msg : errors) {
|
for (String msg : errors) {
|
||||||
|
@ -27,11 +27,12 @@ import java.util.StringJoiner;
|
|||||||
/**
|
/**
|
||||||
* Defines the template definition for a "supporting file", that is any file which is generic and not bound to
|
* Defines the template definition for a "supporting file", that is any file which is generic and not bound to
|
||||||
* api/model definitions and their relevant docs or tests.
|
* api/model definitions and their relevant docs or tests.
|
||||||
*
|
* <p>
|
||||||
* Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
|
* Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
|
||||||
* times according to their target use.
|
* times according to their target use.
|
||||||
*/
|
*/
|
||||||
@Getter public class SupportingFile extends TemplateDefinition {
|
@Getter
|
||||||
|
public class SupportingFile extends TemplateDefinition {
|
||||||
private boolean canOverwrite = true;
|
private boolean canOverwrite = true;
|
||||||
|
|
||||||
public SupportingFile(String templateFile, String destinationFilename) {
|
public SupportingFile(String templateFile, String destinationFilename) {
|
||||||
|
@ -13,8 +13,14 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.*;
|
import java.nio.file.Files;
|
||||||
import java.util.*;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Scanner;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -30,8 +36,8 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
|||||||
/**
|
/**
|
||||||
* Constructs a new instance of a {@link TemplateManager}
|
* Constructs a new instance of a {@link TemplateManager}
|
||||||
*
|
*
|
||||||
* @param options The {@link TemplateManagerOptions} for reading and writing templates
|
* @param options The {@link TemplateManagerOptions} for reading and writing templates
|
||||||
* @param engineAdapter The adaptor to underlying templating engine
|
* @param engineAdapter The adaptor to underlying templating engine
|
||||||
* @param templateLoaders Loaders which define where we look for templates
|
* @param templateLoaders Loaders which define where we look for templates
|
||||||
*/
|
*/
|
||||||
public TemplateManager(
|
public TemplateManager(
|
||||||
@ -87,7 +93,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
|||||||
* Gets a normalized classpath resource location according to OS-specific file separator
|
* Gets a normalized classpath resource location according to OS-specific file separator
|
||||||
*
|
*
|
||||||
* @param name The name of the resource file/directory to find
|
* @param name The name of the resource file/directory to find
|
||||||
*
|
|
||||||
* @return A normalized string according to OS-specific file separator
|
* @return A normalized string according to OS-specific file separator
|
||||||
*/
|
*/
|
||||||
public static String getCPResourcePath(final String name) {
|
public static String getCPResourcePath(final String name) {
|
||||||
@ -152,8 +157,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
|
|||||||
*
|
*
|
||||||
* @param data Input data
|
* @param data Input data
|
||||||
* @param template Input template location
|
* @param template Input template location
|
||||||
* @param target The targeted file output location
|
* @param target The targeted file output location
|
||||||
*
|
|
||||||
* @return The actual file
|
* @return The actual file
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
|
@ -6,7 +6,8 @@ import java.util.Arrays;
|
|||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Getter public enum VendorExtension {
|
@Getter
|
||||||
|
public enum VendorExtension {
|
||||||
|
|
||||||
X_IMPLEMENTS("x-implements", ExtensionLevel.MODEL, "Ability to specify interfaces that model must implements", "empty array"),
|
X_IMPLEMENTS("x-implements", ExtensionLevel.MODEL, "Ability to specify interfaces that model must implements", "empty array"),
|
||||||
X_SPRING_PAGINATED("x-spring-paginated", ExtensionLevel.OPERATION, "Add org.springframework.data.domain.Pageable to controller method. Can be used to handle page & size query parameters", "false"),
|
X_SPRING_PAGINATED("x-spring-paginated", ExtensionLevel.OPERATION, "Add org.springframework.data.domain.Pageable to controller method. Can be used to handle page & size query parameters", "false"),
|
||||||
|
@ -41,9 +41,9 @@ public class AuthParser {
|
|||||||
String[] kvPair = part.split(":");
|
String[] kvPair = part.split(":");
|
||||||
if (kvPair.length == 2) {
|
if (kvPair.length == 2) {
|
||||||
auths.add(new AuthorizationValue(
|
auths.add(new AuthorizationValue(
|
||||||
URLDecoder.decode(kvPair[0], StandardCharsets.UTF_8),
|
URLDecoder.decode(kvPair[0], StandardCharsets.UTF_8),
|
||||||
URLDecoder.decode(kvPair[1], StandardCharsets.UTF_8),
|
URLDecoder.decode(kvPair[1], StandardCharsets.UTF_8),
|
||||||
"header"
|
"header"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -59,7 +59,7 @@ public class AuthParser {
|
|||||||
b.append(",");
|
b.append(",");
|
||||||
}
|
}
|
||||||
b.append(URLEncoder.encode(v.getKeyName(), StandardCharsets.UTF_8))
|
b.append(URLEncoder.encode(v.getKeyName(), StandardCharsets.UTF_8))
|
||||||
.append(":").append(URLEncoder.encode(v.getValue(), StandardCharsets.UTF_8));
|
.append(":").append(URLEncoder.encode(v.getValue(), StandardCharsets.UTF_8));
|
||||||
}
|
}
|
||||||
return b.toString();
|
return b.toString();
|
||||||
} else {
|
} else {
|
||||||
|
@ -48,7 +48,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
|
|||||||
/**
|
/**
|
||||||
* A class which manages the contextual configuration for code generation.
|
* A class which manages the contextual configuration for code generation.
|
||||||
* This includes configuring the generator, templating, and the workflow which orchestrates these.
|
* This includes configuring the generator, templating, and the workflow which orchestrates these.
|
||||||
*
|
* <p>
|
||||||
* This helper also enables the deserialization of {@link GeneratorSettings} via application-specific Jackson JSON usage
|
* This helper also enables the deserialization of {@link GeneratorSettings} via application-specific Jackson JSON usage
|
||||||
* (see {@link DynamicSettings}.
|
* (see {@link DynamicSettings}.
|
||||||
*/
|
*/
|
||||||
@ -109,55 +109,55 @@ public class CodegenConfigurator {
|
|||||||
if (workflowSettings.getGlobalProperties() != null) {
|
if (workflowSettings.getGlobalProperties() != null) {
|
||||||
configurator.globalProperties.putAll(workflowSettings.getGlobalProperties());
|
configurator.globalProperties.putAll(workflowSettings.getGlobalProperties());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getInstantiationTypes() != null) {
|
if (generatorSettings.getInstantiationTypes() != null) {
|
||||||
configurator.instantiationTypes.putAll(generatorSettings.getInstantiationTypes());
|
configurator.instantiationTypes.putAll(generatorSettings.getInstantiationTypes());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getTypeMappings() != null) {
|
if (generatorSettings.getTypeMappings() != null) {
|
||||||
configurator.typeMappings.putAll(generatorSettings.getTypeMappings());
|
configurator.typeMappings.putAll(generatorSettings.getTypeMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getAdditionalProperties() != null) {
|
if (generatorSettings.getAdditionalProperties() != null) {
|
||||||
configurator.additionalProperties.putAll(generatorSettings.getAdditionalProperties());
|
configurator.additionalProperties.putAll(generatorSettings.getAdditionalProperties());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getImportMappings() != null) {
|
if (generatorSettings.getImportMappings() != null) {
|
||||||
configurator.importMappings.putAll(generatorSettings.getImportMappings());
|
configurator.importMappings.putAll(generatorSettings.getImportMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getSchemaMappings() != null) {
|
if (generatorSettings.getSchemaMappings() != null) {
|
||||||
configurator.schemaMappings.putAll(generatorSettings.getSchemaMappings());
|
configurator.schemaMappings.putAll(generatorSettings.getSchemaMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getInlineSchemaNameMappings() != null) {
|
if (generatorSettings.getInlineSchemaNameMappings() != null) {
|
||||||
configurator.inlineSchemaNameMappings.putAll(generatorSettings.getInlineSchemaNameMappings());
|
configurator.inlineSchemaNameMappings.putAll(generatorSettings.getInlineSchemaNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getInlineSchemaOptions() != null) {
|
if (generatorSettings.getInlineSchemaOptions() != null) {
|
||||||
configurator.inlineSchemaOptions.putAll(generatorSettings.getInlineSchemaOptions());
|
configurator.inlineSchemaOptions.putAll(generatorSettings.getInlineSchemaOptions());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getNameMappings() != null) {
|
if (generatorSettings.getNameMappings() != null) {
|
||||||
configurator.nameMappings.putAll(generatorSettings.getNameMappings());
|
configurator.nameMappings.putAll(generatorSettings.getNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getParameterNameMappings() != null) {
|
if (generatorSettings.getParameterNameMappings() != null) {
|
||||||
configurator.parameterNameMappings.putAll(generatorSettings.getParameterNameMappings());
|
configurator.parameterNameMappings.putAll(generatorSettings.getParameterNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getModelNameMappings() != null) {
|
if (generatorSettings.getModelNameMappings() != null) {
|
||||||
configurator.modelNameMappings.putAll(generatorSettings.getModelNameMappings());
|
configurator.modelNameMappings.putAll(generatorSettings.getModelNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getEnumNameMappings() != null) {
|
if (generatorSettings.getEnumNameMappings() != null) {
|
||||||
configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings());
|
configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getOperationIdNameMappings() != null) {
|
if (generatorSettings.getOperationIdNameMappings() != null) {
|
||||||
configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings());
|
configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getOpenapiNormalizer() != null) {
|
if (generatorSettings.getOpenapiNormalizer() != null) {
|
||||||
configurator.openapiNormalizer.putAll(generatorSettings.getOpenapiNormalizer());
|
configurator.openapiNormalizer.putAll(generatorSettings.getOpenapiNormalizer());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getLanguageSpecificPrimitives() != null) {
|
if (generatorSettings.getLanguageSpecificPrimitives() != null) {
|
||||||
configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives());
|
configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getOpenapiGeneratorIgnoreList() != null) {
|
if (generatorSettings.getOpenapiGeneratorIgnoreList() != null) {
|
||||||
configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenapiGeneratorIgnoreList());
|
configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenapiGeneratorIgnoreList());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getReservedWordsMappings() != null) {
|
if (generatorSettings.getReservedWordsMappings() != null) {
|
||||||
configurator.reservedWordsMappings.putAll(generatorSettings.getReservedWordsMappings());
|
configurator.reservedWordsMappings.putAll(generatorSettings.getReservedWordsMappings());
|
||||||
}
|
}
|
||||||
if(generatorSettings.getServerVariables() != null) {
|
if (generatorSettings.getServerVariables() != null) {
|
||||||
configurator.serverVariables.putAll(generatorSettings.getServerVariables());
|
configurator.serverVariables.putAll(generatorSettings.getServerVariables());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -700,12 +700,12 @@ public class CodegenConfigurator {
|
|||||||
|
|
||||||
// Wrap the getUnusedSchemas() in try catch block so it catches the NPE
|
// Wrap the getUnusedSchemas() in try catch block so it catches the NPE
|
||||||
// when the input spec file is not correct
|
// when the input spec file is not correct
|
||||||
try{
|
try {
|
||||||
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
|
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
|
||||||
if (unusedModels != null) {
|
if (unusedModels != null) {
|
||||||
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
|
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
|
||||||
}
|
}
|
||||||
} catch (Exception e){
|
} catch (Exception e) {
|
||||||
System.err.println("[error] There is an error with OpenAPI specification parsed from the input spec file: " + inputSpec);
|
System.err.println("[error] There is an error with OpenAPI specification parsed from the input spec file: " + inputSpec);
|
||||||
System.err.println("[error] Please make sure the spec file has correct format and all required fields are populated with valid value.");
|
System.err.println("[error] Please make sure the spec file has correct format and all required fields are populated with valid value.");
|
||||||
}
|
}
|
||||||
@ -808,6 +808,6 @@ public class CodegenConfigurator {
|
|||||||
.generatorSettings(generatorSettings)
|
.generatorSettings(generatorSettings)
|
||||||
.userDefinedTemplates(userDefinedTemplates);
|
.userDefinedTemplates(userDefinedTemplates);
|
||||||
|
|
||||||
return input.openAPI((OpenAPI)context.getSpecDocument());
|
return input.openAPI((OpenAPI) context.getSpecDocument());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@ import java.util.stream.Collectors;
|
|||||||
public class DynamicSettings {
|
public class DynamicSettings {
|
||||||
/**
|
/**
|
||||||
* -- GETTER --
|
* -- GETTER --
|
||||||
* Gets all "custom" properties included in the config object.
|
* Gets all "custom" properties included in the config object.
|
||||||
*
|
*
|
||||||
* @return All user-specified custom properties.
|
* @return All user-specified custom properties.
|
||||||
*/
|
*/
|
||||||
@ -96,9 +96,10 @@ public class DynamicSettings {
|
|||||||
* <p>Constructor for DynamicSettings.</p>
|
* <p>Constructor for DynamicSettings.</p>
|
||||||
*/
|
*/
|
||||||
@JsonCreator
|
@JsonCreator
|
||||||
public DynamicSettings() { }
|
public DynamicSettings() {
|
||||||
|
}
|
||||||
|
|
||||||
private void excludeSettingsFromDynamicProperties(){
|
private void excludeSettingsFromDynamicProperties() {
|
||||||
Set<String> fieldNames = new HashSet<>();
|
Set<String> fieldNames = new HashSet<>();
|
||||||
for (Field field : GeneratorSettings.class.getDeclaredFields()) {
|
for (Field field : GeneratorSettings.class.getDeclaredFields()) {
|
||||||
fieldNames.add(field.getName());
|
fieldNames.add(field.getName());
|
||||||
|
@ -27,7 +27,7 @@ import java.util.Properties;
|
|||||||
* GlobalSettings encapsulates SystemProperties, since the codegen mechanism heavily relies on a stable,
|
* GlobalSettings encapsulates SystemProperties, since the codegen mechanism heavily relies on a stable,
|
||||||
* non-changing System Property Basis. Using plain System.(get|set|clear)Property raises Race-Conditions in combination
|
* non-changing System Property Basis. Using plain System.(get|set|clear)Property raises Race-Conditions in combination
|
||||||
* with Code, that uses System.setProperties (e.g. maven-surefire-plugin).
|
* with Code, that uses System.setProperties (e.g. maven-surefire-plugin).
|
||||||
*
|
* <p>
|
||||||
* This provides a set of properties specific to the executing thread, such that the generator may not modify system properties
|
* This provides a set of properties specific to the executing thread, such that the generator may not modify system properties
|
||||||
* consumed by other threads.
|
* consumed by other threads.
|
||||||
*
|
*
|
||||||
|
@ -1,32 +1,24 @@
|
|||||||
package org.openapitools.codegen.config;
|
package org.openapitools.codegen.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||||
|
import com.google.common.collect.ImmutableMap;
|
||||||
|
import io.swagger.parser.OpenAPIParser;
|
||||||
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
|
import io.swagger.v3.parser.core.models.ParseOptions;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.nio.file.StandardOpenOption;
|
import java.nio.file.StandardOpenOption;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
|
||||||
import com.google.common.collect.ImmutableMap;
|
|
||||||
|
|
||||||
import io.swagger.parser.OpenAPIParser;
|
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
|
||||||
import io.swagger.v3.parser.core.models.ParseOptions;
|
|
||||||
|
|
||||||
public class MergedSpecBuilder {
|
public class MergedSpecBuilder {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class);
|
||||||
@ -59,8 +51,8 @@ public class MergedSpecBuilder {
|
|||||||
LOGGER.info("Reading spec: {}", specPath);
|
LOGGER.info("Reading spec: {}", specPath);
|
||||||
|
|
||||||
OpenAPI result = new OpenAPIParser()
|
OpenAPI result = new OpenAPIParser()
|
||||||
.readLocation(specPath, new ArrayList<>(), options)
|
.readLocation(specPath, new ArrayList<>(), options)
|
||||||
.getOpenAPI();
|
.getOpenAPI();
|
||||||
|
|
||||||
if (openapiVersion == null) {
|
if (openapiVersion == null) {
|
||||||
openapiVersion = result.getOpenapi();
|
openapiVersion = result.getOpenapi();
|
||||||
@ -93,11 +85,11 @@ public class MergedSpecBuilder {
|
|||||||
Map<String, Object> paths = new HashMap<>();
|
Map<String, Object> paths = new HashMap<>();
|
||||||
spec.put("paths", paths);
|
spec.put("paths", paths);
|
||||||
|
|
||||||
for(SpecWithPaths specWithPaths : allPaths) {
|
for (SpecWithPaths specWithPaths : allPaths) {
|
||||||
for (String path : specWithPaths.paths) {
|
for (String path : specWithPaths.paths) {
|
||||||
String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1");
|
String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1");
|
||||||
paths.put(path, ImmutableMap.of(
|
paths.put(path, ImmutableMap.of(
|
||||||
"$ref", specRelatedPath
|
"$ref", specRelatedPath
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -109,12 +101,12 @@ public class MergedSpecBuilder {
|
|||||||
Map<String, Object> map = new HashMap<>();
|
Map<String, Object> map = new HashMap<>();
|
||||||
map.put("openapi", openapiVersion);
|
map.put("openapi", openapiVersion);
|
||||||
map.put("info", ImmutableMap.of(
|
map.put("info", ImmutableMap.of(
|
||||||
"title", "merged spec",
|
"title", "merged spec",
|
||||||
"description", "merged spec",
|
"description", "merged spec",
|
||||||
"version", "1.0.0"
|
"version", "1.0.0"
|
||||||
));
|
));
|
||||||
map.put("servers", Collections.singleton(
|
map.put("servers", Collections.singleton(
|
||||||
ImmutableMap.of("url", "http://localhost:8080")
|
ImmutableMap.of("url", "http://localhost:8080")
|
||||||
));
|
));
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
@ -123,9 +115,9 @@ public class MergedSpecBuilder {
|
|||||||
Path rootDirectory = new File(inputSpecRootDirectory).toPath();
|
Path rootDirectory = new File(inputSpecRootDirectory).toPath();
|
||||||
try (Stream<Path> pathStream = Files.walk(rootDirectory)) {
|
try (Stream<Path> pathStream = Files.walk(rootDirectory)) {
|
||||||
return pathStream
|
return pathStream
|
||||||
.filter(path -> !Files.isDirectory(path))
|
.filter(path -> !Files.isDirectory(path))
|
||||||
.map(path -> rootDirectory.relativize(path).toString())
|
.map(path -> rootDirectory.relativize(path).toString())
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new RuntimeException("Exception while listing files in spec root directory: " + inputSpecRootDirectory, e);
|
throw new RuntimeException("Exception while listing files in spec root directory: " + inputSpecRootDirectory, e);
|
||||||
}
|
}
|
||||||
@ -134,10 +126,12 @@ public class MergedSpecBuilder {
|
|||||||
private void deleteMergedFileFromPreviousRun() {
|
private void deleteMergedFileFromPreviousRun() {
|
||||||
try {
|
try {
|
||||||
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json"));
|
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json"));
|
||||||
} catch (IOException e) { }
|
} catch (IOException e) {
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml"));
|
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml"));
|
||||||
} catch (IOException e) { }
|
} catch (IOException e) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class SpecWithPaths {
|
private static class SpecWithPaths {
|
||||||
|
@ -248,7 +248,7 @@ public class ExampleGenerator {
|
|||||||
} else if (ModelUtils.isArraySchema(property)) {
|
} else if (ModelUtils.isArraySchema(property)) {
|
||||||
Schema innerType = ModelUtils.getSchemaItems(property);
|
Schema innerType = ModelUtils.getSchemaItems(property);
|
||||||
if (innerType != null) {
|
if (innerType != null) {
|
||||||
int arrayLength = null == property.getMaxItems() ? 2 : property.getMaxItems();
|
int arrayLength = null == property.getMaxItems() ? 2 : property.getMaxItems();
|
||||||
// avoid memory issues by limiting to max. 5 items
|
// avoid memory issues by limiting to max. 5 items
|
||||||
arrayLength = Math.min(arrayLength, 5);
|
arrayLength = Math.min(arrayLength, 5);
|
||||||
Object[] objectProperties = new Object[arrayLength];
|
Object[] objectProperties = new Object[arrayLength];
|
||||||
@ -398,10 +398,11 @@ public class ExampleGenerator {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Transverse and resolves all property examples for `allOf` composed schemas into `values` map object
|
* Transverse and resolves all property examples for `allOf` composed schemas into `values` map object
|
||||||
* @param mediaType MIME type
|
*
|
||||||
* @param schema OAS schema
|
* @param mediaType MIME type
|
||||||
|
* @param schema OAS schema
|
||||||
* @param processedModels Set containing all processed models
|
* @param processedModels Set containing all processed models
|
||||||
* @param values Example value map
|
* @param values Example value map
|
||||||
*/
|
*/
|
||||||
private void resolveAllOfSchemaProperties(String mediaType, Schema schema, Set<String> processedModels, Map<String, Object> values) {
|
private void resolveAllOfSchemaProperties(String mediaType, Schema schema, Set<String> processedModels, Map<String, Object> values) {
|
||||||
List<Schema> interfaces = schema.getAllOf();
|
List<Schema> interfaces = schema.getAllOf();
|
||||||
|
@ -172,7 +172,7 @@ public class XmlExampleGenerator {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the example string value for the given schema.
|
* Get the example string value for the given schema.
|
||||||
*
|
* <p>
|
||||||
* If an example value was not provided in the specification, a default will be generated.
|
* If an example value was not provided in the specification, a default will be generated.
|
||||||
*
|
*
|
||||||
* @param schema Schema to get example string for
|
* @param schema Schema to get example string for
|
||||||
|
@ -2,8 +2,8 @@ package org.openapitools.codegen.exceptions;
|
|||||||
|
|
||||||
public class ProtoBufIndexComputationException extends Exception {
|
public class ProtoBufIndexComputationException extends Exception {
|
||||||
|
|
||||||
public ProtoBufIndexComputationException(String reason) {
|
public ProtoBufIndexComputationException(String reason) {
|
||||||
super(reason);
|
super(reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.util.*;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
|
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
|
||||||
|
|
||||||
@ -113,15 +116,15 @@ public class CodegenIgnoreProcessor {
|
|||||||
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
|
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
|
||||||
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
|
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
|
||||||
while ((line = reader.readLine()) != null) {
|
while ((line = reader.readLine()) != null) {
|
||||||
if(
|
if (
|
||||||
//: A blank line matches no files, so it can serve as a separator for readability.
|
//: A blank line matches no files, so it can serve as a separator for readability.
|
||||||
line.length() == 0
|
line.length() == 0
|
||||||
) continue;
|
) continue;
|
||||||
|
|
||||||
Rule rule = Rule.create(line);
|
Rule rule = Rule.create(line);
|
||||||
|
|
||||||
// rule could be null here if it's a COMMENT, for example
|
// rule could be null here if it's a COMMENT, for example
|
||||||
if(rule != null) {
|
if (rule != null) {
|
||||||
if (Boolean.TRUE.equals(rule.getNegated())) {
|
if (Boolean.TRUE.equals(rule.getNegated())) {
|
||||||
inclusionRules.add(rule);
|
inclusionRules.add(rule);
|
||||||
} else {
|
} else {
|
||||||
@ -140,12 +143,12 @@ public class CodegenIgnoreProcessor {
|
|||||||
* @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
|
* @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
|
||||||
*/
|
*/
|
||||||
public boolean allowsFile(final File targetFile) {
|
public boolean allowsFile(final File targetFile) {
|
||||||
if(this.ignoreFile == null) return true;
|
if (this.ignoreFile == null) return true;
|
||||||
|
|
||||||
File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
|
File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
|
||||||
boolean directoryExcluded = false;
|
boolean directoryExcluded = false;
|
||||||
boolean exclude = false;
|
boolean exclude = false;
|
||||||
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
|
if (exclusionRules.size() == 0 && inclusionRules.size() == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -154,12 +157,12 @@ public class CodegenIgnoreProcessor {
|
|||||||
Rule current = exclusionRules.get(i);
|
Rule current = exclusionRules.get(i);
|
||||||
Rule.Operation op = current.evaluate(file.getPath());
|
Rule.Operation op = current.evaluate(file.getPath());
|
||||||
|
|
||||||
switch (op){
|
switch (op) {
|
||||||
case EXCLUDE:
|
case EXCLUDE:
|
||||||
exclude = true;
|
exclude = true;
|
||||||
|
|
||||||
// Include rule can't override rules that exclude a file by some parent directory.
|
// Include rule can't override rules that exclude a file by some parent directory.
|
||||||
if(current instanceof DirectoryRule) {
|
if (current instanceof DirectoryRule) {
|
||||||
directoryExcluded = true;
|
directoryExcluded = true;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -174,7 +177,7 @@ public class CodegenIgnoreProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(exclude) {
|
if (exclude) {
|
||||||
// Only need to process inclusion rules if we've been excluded
|
// Only need to process inclusion rules if we've been excluded
|
||||||
for (int i = 0; exclude && i < inclusionRules.size(); i++) {
|
for (int i = 0; exclude && i < inclusionRules.size(); i++) {
|
||||||
Rule current = inclusionRules.get(i);
|
Rule current = inclusionRules.get(i);
|
||||||
@ -182,8 +185,8 @@ public class CodegenIgnoreProcessor {
|
|||||||
|
|
||||||
// At this point exclude=true means the file should be ignored.
|
// At this point exclude=true means the file should be ignored.
|
||||||
// op == INCLUDE means we have to flip that flag.
|
// op == INCLUDE means we have to flip that flag.
|
||||||
if(op.equals(Rule.Operation.INCLUDE)) {
|
if (op.equals(Rule.Operation.INCLUDE)) {
|
||||||
if(current instanceof DirectoryRule && directoryExcluded) {
|
if (current instanceof DirectoryRule && directoryExcluded) {
|
||||||
// e.g
|
// e.g
|
||||||
// baz/
|
// baz/
|
||||||
// !foo/bar/baz/
|
// !foo/bar/baz/
|
||||||
@ -216,7 +219,7 @@ public class CodegenIgnoreProcessor {
|
|||||||
/**
|
/**
|
||||||
* Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
|
* Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
|
||||||
* files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
|
* files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
|
||||||
*
|
* <p>
|
||||||
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
|
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
|
||||||
*
|
*
|
||||||
* @return A {@link Collections#unmodifiableList(List)} of rules which define exclusions by patterns in the ignore file.
|
* @return A {@link Collections#unmodifiableList(List)} of rules which define exclusions by patterns in the ignore file.
|
||||||
|
@ -32,7 +32,7 @@ public class DirectoryRule extends FileRule {
|
|||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.append("glob:");
|
sb.append("glob:");
|
||||||
sb.append(pattern);
|
sb.append(pattern);
|
||||||
if(!pattern.endsWith("/")) sb.append("/");
|
if (!pattern.endsWith("/")) sb.append("/");
|
||||||
directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
|
directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
|
||||||
sb.append("**");
|
sb.append("**");
|
||||||
contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
|
contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
|
||||||
|
@ -33,5 +33,7 @@ public class EverythingRule extends Rule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; }
|
protected Operation getExcludeOperation() {
|
||||||
|
return Operation.EXCLUDE_AND_TERMINATE;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -27,7 +27,7 @@ public class FileRule extends Rule {
|
|||||||
|
|
||||||
FileRule(List<Part> syntax, String definition) {
|
FileRule(List<Part> syntax, String definition) {
|
||||||
super(syntax, definition);
|
super(syntax, definition);
|
||||||
matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern());
|
matcher = FileSystems.getDefault().getPathMatcher("glob:" + this.getPattern());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -23,7 +23,8 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class IgnoreLineParser {
|
public class IgnoreLineParser {
|
||||||
@Getter enum Token {
|
@Getter
|
||||||
|
enum Token {
|
||||||
MATCH_ALL("**"),
|
MATCH_ALL("**"),
|
||||||
MATCH_ANY("*"),
|
MATCH_ANY("*"),
|
||||||
ESCAPED_EXCLAMATION("\\!"),
|
ESCAPED_EXCLAMATION("\\!"),
|
||||||
@ -84,8 +85,8 @@ public class IgnoreLineParser {
|
|||||||
|
|
||||||
if (Token.MATCH_ANY.pattern.equals(next)) {
|
if (Token.MATCH_ANY.pattern.equals(next)) {
|
||||||
// peek ahead for invalid pattern. Slightly inefficient, but acceptable.
|
// peek ahead for invalid pattern. Slightly inefficient, but acceptable.
|
||||||
if ((i+2 < totalLength - 1) &&
|
if ((i + 2 < totalLength - 1) &&
|
||||||
String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) {
|
String.valueOf(characters[i + 2]).equals(Token.MATCH_ANY.pattern)) {
|
||||||
// It doesn't matter where we are in the pattern, *** is invalid.
|
// It doesn't matter where we are in the pattern, *** is invalid.
|
||||||
throw new ParserException("The pattern *** is invalid.");
|
throw new ParserException("The pattern *** is invalid.");
|
||||||
}
|
}
|
||||||
@ -129,7 +130,7 @@ public class IgnoreLineParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parts.add(new Part(Token.PATH_DELIM));
|
parts.add(new Part(Token.PATH_DELIM));
|
||||||
if(Token.PATH_DELIM.pattern.equals(next)) {
|
if (Token.PATH_DELIM.pattern.equals(next)) {
|
||||||
// ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in //
|
// ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in //
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,8 @@ import lombok.Getter;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Getter public class InvalidRule extends Rule {
|
@Getter
|
||||||
|
public class InvalidRule extends Rule {
|
||||||
private final String reason;
|
private final String reason;
|
||||||
|
|
||||||
InvalidRule(List<Part> syntax, String definition, String reason) {
|
InvalidRule(List<Part> syntax, String definition, String reason) {
|
||||||
|
@ -19,7 +19,8 @@ package org.openapitools.codegen.ignore.rules;
|
|||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
@Getter class Part {
|
@Getter
|
||||||
|
class Part {
|
||||||
private final IgnoreLineParser.Token token;
|
private final IgnoreLineParser.Token token;
|
||||||
private final String value;
|
private final String value;
|
||||||
|
|
||||||
|
@ -36,12 +36,12 @@ public class RootedFileRule extends Rule {
|
|||||||
definedExtension = getExtensionPart(definition, separatorIndex);
|
definedExtension = getExtensionPart(definition, separatorIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getFilenamePart(final String input, int stopIndex){
|
private String getFilenamePart(final String input, int stopIndex) {
|
||||||
return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length());
|
return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getExtensionPart(final String input, int stopIndex) {
|
private String getExtensionPart(final String input, int stopIndex) {
|
||||||
return input.substring(stopIndex > 0 ? stopIndex+1: input.length());
|
return input.substring(stopIndex > 0 ? stopIndex + 1 : input.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -51,13 +51,13 @@ public class RootedFileRule extends Rule {
|
|||||||
// relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore.
|
// relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore.
|
||||||
boolean isSingleFile = relativePath.lastIndexOf("/") <= 0;
|
boolean isSingleFile = relativePath.lastIndexOf("/") <= 0;
|
||||||
|
|
||||||
if(isSingleFile) {
|
if (isSingleFile) {
|
||||||
int separatorIndex = relativePath.lastIndexOf(".");
|
int separatorIndex = relativePath.lastIndexOf(".");
|
||||||
final String filename = getFilenamePart(relativePath, separatorIndex);
|
final String filename = getFilenamePart(relativePath, separatorIndex);
|
||||||
final String extension = getExtensionPart(relativePath, separatorIndex);
|
final String extension = getExtensionPart(relativePath, separatorIndex);
|
||||||
boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern());
|
boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern());
|
||||||
|
|
||||||
if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
|
if (extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
|
||||||
// TODO: Evaluate any other escape requirements here.
|
// TODO: Evaluate any other escape requirements here.
|
||||||
Pattern regex = Pattern.compile(
|
Pattern regex = Pattern.compile(
|
||||||
definedFilename
|
definedFilename
|
||||||
|
@ -38,7 +38,7 @@ public abstract class Rule {
|
|||||||
public abstract Boolean matches(String relativePath);
|
public abstract Boolean matches(String relativePath);
|
||||||
|
|
||||||
protected String getPattern() {
|
protected String getPattern() {
|
||||||
if(syntax == null) return this.definition;
|
if (syntax == null) return this.definition;
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
for (Part current : syntax) {
|
for (Part current : syntax) {
|
||||||
@ -75,7 +75,7 @@ public abstract class Rule {
|
|||||||
|
|
||||||
public Operation evaluate(String relativePath) {
|
public Operation evaluate(String relativePath) {
|
||||||
if (Boolean.TRUE.equals(matches(relativePath))) {
|
if (Boolean.TRUE.equals(matches(relativePath))) {
|
||||||
if(Boolean.TRUE.equals(this.getNegated())) {
|
if (Boolean.TRUE.equals(this.getNegated())) {
|
||||||
return this.getIncludeOperation();
|
return this.getIncludeOperation();
|
||||||
}
|
}
|
||||||
return this.getExcludeOperation();
|
return this.getExcludeOperation();
|
||||||
@ -83,8 +83,13 @@ public abstract class Rule {
|
|||||||
return Operation.NOOP;
|
return Operation.NOOP;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Operation getIncludeOperation(){ return Operation.INCLUDE; }
|
protected Operation getIncludeOperation() {
|
||||||
protected Operation getExcludeOperation(){ return Operation.EXCLUDE; }
|
return Operation.INCLUDE;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Operation getExcludeOperation() {
|
||||||
|
return Operation.EXCLUDE;
|
||||||
|
}
|
||||||
|
|
||||||
public static Rule create(String definition) {
|
public static Rule create(String definition) {
|
||||||
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
|
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
|
||||||
|
@ -27,12 +27,7 @@ import io.swagger.v3.oas.models.servers.Server;
|
|||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.openapitools.codegen.*;
|
import org.openapitools.codegen.*;
|
||||||
import org.openapitools.codegen.meta.features.ClientModificationFeature;
|
import org.openapitools.codegen.meta.features.*;
|
||||||
import org.openapitools.codegen.meta.features.DocumentationFeature;
|
|
||||||
import org.openapitools.codegen.meta.features.GlobalFeature;
|
|
||||||
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
|
|
||||||
import org.openapitools.codegen.meta.features.SecurityFeature;
|
|
||||||
import org.openapitools.codegen.meta.features.WireFormatFeature;
|
|
||||||
import org.openapitools.codegen.model.ModelMap;
|
import org.openapitools.codegen.model.ModelMap;
|
||||||
import org.openapitools.codegen.model.ModelsMap;
|
import org.openapitools.codegen.model.ModelsMap;
|
||||||
import org.openapitools.codegen.model.OperationMap;
|
import org.openapitools.codegen.model.OperationMap;
|
||||||
|
@ -18,10 +18,9 @@
|
|||||||
package org.openapitools.codegen.languages;
|
package org.openapitools.codegen.languages;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
import com.samskivert.mustache.Mustache.Lambda;
|
|
||||||
import com.samskivert.mustache.Mustache;
|
import com.samskivert.mustache.Mustache;
|
||||||
|
import com.samskivert.mustache.Mustache.Lambda;
|
||||||
import com.samskivert.mustache.Template;
|
import com.samskivert.mustache.Template;
|
||||||
|
|
||||||
import io.swagger.v3.oas.models.media.Schema;
|
import io.swagger.v3.oas.models.media.Schema;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@ -504,7 +503,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** If the value can be parsed as a double, returns the value, otherwise returns null */
|
/**
|
||||||
|
* If the value can be parsed as a double, returns the value, otherwise returns null
|
||||||
|
*/
|
||||||
public static Double asDouble(String strNum) {
|
public static Double asDouble(String strNum) {
|
||||||
if (strNum == null) {
|
if (strNum == null) {
|
||||||
return null;
|
return null;
|
||||||
@ -516,7 +517,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** If the value can be parsed as an integer, returns the value, otherwise returns null */
|
/**
|
||||||
|
* If the value can be parsed as an integer, returns the value, otherwise returns null
|
||||||
|
*/
|
||||||
public static Integer asInteger(String strNum) {
|
public static Integer asInteger(String strNum) {
|
||||||
if (strNum == null) {
|
if (strNum == null) {
|
||||||
return null;
|
return null;
|
||||||
@ -751,7 +754,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
|
|
||||||
property.name = patchPropertyName(model, property.name);
|
property.name = patchPropertyName(model, property.name);
|
||||||
|
|
||||||
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" };
|
String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
|
||||||
|
|
||||||
Arrays.stream(nestedTypes).forEach(nestedType -> {
|
Arrays.stream(nestedTypes).forEach(nestedType -> {
|
||||||
// fix incorrect data types for maps of maps
|
// fix incorrect data types for maps of maps
|
||||||
@ -835,6 +838,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
httpStatusesWithReturn.add(status);
|
httpStatusesWithReturn.add(status);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private HashMap<String, String> duplicateOf = new HashMap<String, String>();
|
private HashMap<String, String> duplicateOf = new HashMap<String, String>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -876,7 +880,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String code = response.code.toLowerCase(Locale.ROOT);
|
String code = response.code.toLowerCase(Locale.ROOT);
|
||||||
switch(code) {
|
switch (code) {
|
||||||
case "default":
|
case "default":
|
||||||
case "0":
|
case "0":
|
||||||
postProcessResponseCode(response, "Default", httpStatusesWithReturn);
|
postProcessResponseCode(response, "Default", httpStatusesWithReturn);
|
||||||
@ -1242,7 +1246,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void processOperation(CodegenOperation operation) {
|
protected void processOperation(CodegenOperation operation) {
|
||||||
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" };
|
String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
|
||||||
|
|
||||||
Arrays.stream(nestedTypes).forEach(nestedType -> {
|
Arrays.stream(nestedTypes).forEach(nestedType -> {
|
||||||
if (operation.returnProperty != null && operation.returnType.contains("<" + nestedType + ">") && operation.returnProperty.items != null) {
|
if (operation.returnProperty != null && operation.returnType.contains("<" + nestedType + ">") && operation.returnProperty.items != null) {
|
||||||
@ -1707,8 +1711,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
* @param name The original name
|
* @param name The original name
|
||||||
* @return The adjusted name
|
* @return The adjusted name
|
||||||
*/
|
*/
|
||||||
private String adjustNamingStyle(String name)
|
private String adjustNamingStyle(String name) {
|
||||||
{
|
|
||||||
switch (getEnumPropertyNaming()) {
|
switch (getEnumPropertyNaming()) {
|
||||||
case camelCase:
|
case camelCase:
|
||||||
// NOTE: Removes hyphens and underscores
|
// NOTE: Removes hyphens and underscores
|
||||||
@ -1765,7 +1768,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
return (this.getValueTypes().contains(var.dataType) || var.isEnum);
|
return (this.getValueTypes().contains(var.dataType) || var.isEnum);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected boolean useNet60OrLater() { return false; }
|
protected boolean useNet60OrLater() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
protected boolean useDateOnly() {
|
protected boolean useDateOnly() {
|
||||||
return useNet60OrLater() && !useDateTimeForDateFlag;
|
return useNet60OrLater() && !useDateTimeForDateFlag;
|
||||||
@ -1915,7 +1920,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
|
|
||||||
// only process files with .cs extension
|
// only process files with .cs extension
|
||||||
if ("cs".equals(FilenameUtils.getExtension(file.toString()))) {
|
if ("cs".equals(FilenameUtils.getExtension(file.toString()))) {
|
||||||
this.executePostProcessor(new String[] {csharpPostProcessFile, file.toString()});
|
this.executePostProcessor(new String[]{csharpPostProcessFile, file.toString()});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1936,12 +1941,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
Pattern hasModifiers = Pattern.compile(".*/[gmiyuvsdlnx]+$");
|
Pattern hasModifiers = Pattern.compile(".*/[gmiyuvsdlnx]+$");
|
||||||
|
|
||||||
int end = hasModifiers.matcher(pattern).find()
|
int end = hasModifiers.matcher(pattern).find()
|
||||||
? pattern.lastIndexOf('/')
|
? pattern.lastIndexOf('/')
|
||||||
: pattern.length() - 1;
|
: pattern.length() - 1;
|
||||||
|
|
||||||
int start = pattern.startsWith("/")
|
int start = pattern.startsWith("/")
|
||||||
? 1
|
? 1
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
Map<Character, String> optionsMap = new HashMap<Character, String>();
|
Map<Character, String> optionsMap = new HashMap<Character, String>();
|
||||||
optionsMap.put('i', "IgnoreCase");
|
optionsMap.put('i', "IgnoreCase");
|
||||||
@ -1956,7 +1961,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
|
|||||||
for (char c : pattern.substring(end).toCharArray()) {
|
for (char c : pattern.substring(end).toCharArray()) {
|
||||||
if (optionsMap.containsKey(c)) {
|
if (optionsMap.containsKey(c)) {
|
||||||
modifiers.add(optionsMap.get(c));
|
modifiers.add(optionsMap.get(c));
|
||||||
} else if (c == 'l'){
|
} else if (c == 'l') {
|
||||||
modifiers.remove("CultureInvariant");
|
modifiers.remove("CultureInvariant");
|
||||||
} else {
|
} else {
|
||||||
vendorExtensions.put("x-modifier-" + c, c);
|
vendorExtensions.put("x-modifier-" + c, c);
|
||||||
|
@ -19,15 +19,14 @@ package org.openapitools.codegen.languages;
|
|||||||
|
|
||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
import com.samskivert.mustache.Mustache.Lambda;
|
import com.samskivert.mustache.Mustache.Lambda;
|
||||||
|
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import io.swagger.v3.oas.models.media.Schema;
|
import io.swagger.v3.oas.models.media.Schema;
|
||||||
import io.swagger.v3.oas.models.servers.Server;
|
import io.swagger.v3.oas.models.servers.Server;
|
||||||
import io.swagger.v3.oas.models.servers.ServerVariables;
|
|
||||||
import io.swagger.v3.oas.models.servers.ServerVariable;
|
import io.swagger.v3.oas.models.servers.ServerVariable;
|
||||||
import org.openapitools.codegen.*;
|
import io.swagger.v3.oas.models.servers.ServerVariables;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.openapitools.codegen.*;
|
||||||
import org.openapitools.codegen.model.ModelMap;
|
import org.openapitools.codegen.model.ModelMap;
|
||||||
import org.openapitools.codegen.model.ModelsMap;
|
import org.openapitools.codegen.model.ModelsMap;
|
||||||
import org.openapitools.codegen.templating.mustache.IndentedLambda;
|
import org.openapitools.codegen.templating.mustache.IndentedLambda;
|
||||||
@ -38,11 +37,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
|
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
|
||||||
private final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
|
private final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
|
||||||
@ -348,7 +343,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
|
|||||||
}
|
}
|
||||||
// only process files with cpp extension
|
// only process files with cpp extension
|
||||||
if ("cpp".equals(FilenameUtils.getExtension(file.toString())) || "h".equals(FilenameUtils.getExtension(file.toString()))) {
|
if ("cpp".equals(FilenameUtils.getExtension(file.toString())) || "h".equals(FilenameUtils.getExtension(file.toString()))) {
|
||||||
this.executePostProcessor(new String[] {cppPostProcessFile, file.toString()});
|
this.executePostProcessor(new String[]{cppPostProcessFile, file.toString()});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -806,7 +806,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
|
|||||||
// process all files with dart extension
|
// process all files with dart extension
|
||||||
if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
|
if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
|
||||||
// currently supported is "dartfmt -w" and "dart format"
|
// currently supported is "dartfmt -w" and "dart format"
|
||||||
this.executePostProcessor(new String[] {dartPostProcessFile, file.toString()});
|
this.executePostProcessor(new String[]{dartPostProcessFile, file.toString()});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user