Skip to content

#33 #45

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Dec 5, 2019
Merged

#33 #45

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import com.github.hauner.openapi.spring.model.datatypes.NoneDataType
import com.github.hauner.openapi.spring.model.datatypes.OffsetDateTimeDataType
import com.github.hauner.openapi.spring.model.datatypes.SetDataType
import com.github.hauner.openapi.spring.model.datatypes.StringDataType
import com.github.hauner.openapi.spring.model.datatypes.StringEnumDataType

/**
* Converter to map OpenAPI schemas to Java data types.
Expand Down Expand Up @@ -88,7 +89,7 @@ class DataTypeConverter {
createObjectDataType (dataTypeInfo, dataTypes)

} else {
createSimpleDataType (dataTypeInfo)
createSimpleDataType (dataTypeInfo, dataTypes)
}
}

Expand Down Expand Up @@ -153,7 +154,7 @@ class DataTypeConverter {
objectType
}

private DataType createSimpleDataType (SchemaInfo schemaInfo) {
private DataType createSimpleDataType (SchemaInfo schemaInfo, DataTypes dataTypes) {

TargetType targetType = getMappedDataType (new PrimitiveSchemaType(schemaInfo))
if (targetType) {
Expand Down Expand Up @@ -190,7 +191,7 @@ class DataTypeConverter {
simpleType = new BooleanDataType ()
break
case 'string':
simpleType = new StringDataType ()
simpleType = createStringDataType (schemaInfo, dataTypes)
break
case 'string/date':
simpleType = new LocalDateDataType ()
Expand All @@ -205,6 +206,22 @@ class DataTypeConverter {
simpleType
}

private DataType createStringDataType (SchemaInfo info, DataTypes dataTypes) {
if (!info.isEnum()) {
return new StringDataType ()
}

// in case of an inline definition the name may be lowercase, make sure the enum
// class gets an uppercase name!
def enumType = new StringEnumDataType (
type: info.name.capitalize (),
pkg: [options.packageName, 'model'].join ('.'),
values: info.enumValues)

dataTypes.add (enumType)
enumType
}

TargetType getMappedDataType (SchemaType schemaType) {
// check endpoint mappings
List<TypeMappingX> endpointMatches = schemaType.matchEndpointMapping (options.typeMappings)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ class SchemaInfo {
schema.$ref != null
}

boolean isEnum () {
schema.enum != null
}

List<?> getEnumValues () {
schema.enum
}

private boolean hasExtensions () {
schema.extensions != null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import com.github.hauner.openapi.api.OpenApiGeneratr
import com.github.hauner.openapi.spring.converter.ApiConverter
import com.github.hauner.openapi.spring.converter.ApiOptions
import com.github.hauner.openapi.spring.writer.ApiWriter
import com.github.hauner.openapi.spring.writer.DataTypeWriter
import com.github.hauner.openapi.spring.writer.HeaderWriter
import com.github.hauner.openapi.spring.writer.InterfaceWriter
import com.github.hauner.openapi.spring.writer.MethodWriter
import com.github.hauner.openapi.spring.writer.StringEnumWriter
import io.swagger.v3.parser.OpenAPIV3Parser
import io.swagger.v3.parser.core.models.ParseOptions
import io.swagger.v3.parser.core.models.SwaggerParseResult
Expand Down Expand Up @@ -63,10 +65,13 @@ class SpringGeneratr implements OpenApiGeneratr<SpringGeneratrOptions> {
def cv = new ApiConverter(options)
def api = cv.convert (result.openAPI)

def headerWriter = new HeaderWriter()
def writer = new ApiWriter (options,
new InterfaceWriter(
headerWriter: new HeaderWriter(),
methodWriter: new MethodWriter())
headerWriter: headerWriter,
methodWriter: new MethodWriter()),
new DataTypeWriter(headerWriter: headerWriter),
new StringEnumWriter(headerWriter: headerWriter)
)

writer.write (api)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package com.github.hauner.openapi.spring.model

import com.github.hauner.openapi.spring.model.datatypes.DataType
import com.github.hauner.openapi.spring.model.datatypes.ObjectDataType
import com.github.hauner.openapi.spring.model.datatypes.StringEnumDataType

/**
* Container for Java data types from OpenAPI '#/component/schemas'.
Expand Down Expand Up @@ -49,6 +50,18 @@ class DataTypes {
} as List<ObjectDataType>
}

/**
* provides the enum data types (model classes) used by the api endpoints. For this object
* the generatr will create enum classes.
*
* @return list of enum data types
*/
List<StringEnumDataType> getEnumDataTypes () {
types.values ().findAll {
it instanceof StringEnumDataType
} as List<StringEnumDataType>
}

void add (List<DataType> dataTypes) {
dataTypes.each {
types.put (it.name, it)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,39 @@
* limitations under the License.
*/

package com.github.hauner.openapi.spring.converter
package com.github.hauner.openapi.spring.model.datatypes

import spock.lang.Specification
/**
* OpenAPI type 'string' with enum constraint maps to enum class.
*
* @author Martin Hauner
*/
class StringEnumDataType implements DataType {

String type
String pkg = 'unknown'
List<String> values = []

@Override
String getName () {
type
}

@Override
String getPackageName () {
pkg
}

class ApiConverterSchemaSpec extends Specification {
@Override
Set<String> getImports () {
[[packageName, name].join ('.')]
}

@Override
Set<String> getReferencedImports () {
[]
}

}


Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package com.github.hauner.openapi.spring.writer
import com.github.hauner.openapi.spring.converter.ApiOptions
import com.github.hauner.openapi.spring.model.Api
import com.github.hauner.openapi.spring.model.datatypes.ObjectDataType
import com.github.hauner.openapi.spring.model.datatypes.StringEnumDataType
import groovy.util.logging.Slf4j

/**
Expand All @@ -32,6 +33,7 @@ class ApiWriter {
private ApiOptions options
InterfaceWriter interfaceWriter
DataTypeWriter dataTypeWriter
StringEnumWriter enumWriter

File apiFolder
File modelFolder
Expand All @@ -41,12 +43,17 @@ class ApiWriter {
this.options = options
this.interfaceWriter = interfaceWriter
this.dataTypeWriter = new DataTypeWriter(headerWriter: new HeaderWriter ())
this.enumWriter = new StringEnumWriter(headerWriter: new HeaderWriter ())
}

ApiWriter(ApiOptions options, InterfaceWriter interfaceWriter, DataTypeWriter dataTypeWriter) {
ApiWriter(ApiOptions options,
InterfaceWriter interfaceWriter,
DataTypeWriter dataTypeWriter,
StringEnumWriter enumWriter) {
this.options = options
this.interfaceWriter = interfaceWriter
this.dataTypeWriter = dataTypeWriter
this.enumWriter = enumWriter
}

void write(Api api) {
Expand All @@ -65,6 +72,13 @@ class ApiWriter {
dataTypeWriter.write (writer, it as ObjectDataType)
writer.close ()
}

api.models.enumDataTypes.each {
def target = new File (modelFolder, "${it.name}.java")
def writer = new FileWriter(target)
enumWriter.write (writer, it as StringEnumDataType)
writer.close ()
}
}

private void createTargetFolders () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,5 @@ class DataTypeWriter {
new ImportFilter ().filter (packageName, imports)
.sort ()
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2019 the original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.github.hauner.openapi.spring.writer

import com.github.hauner.openapi.spring.model.datatypes.StringEnumDataType
import com.github.hauner.openapi.support.Identifier

/**
* Writer for String enum.
*
* @author Martin Hauner
*/
class StringEnumWriter {

HeaderWriter headerWriter

void write (Writer target, StringEnumDataType dataType) {
headerWriter.write (target)
target.write ("package ${dataType.packageName};\n\n")

target.write ("public enum ${dataType.type} {\n\n")

def values = []
dataType.values.each {
values.add (" ${Identifier.toEnum (it)}(\"${it}\")")
}
target.write (values.join (",\n") + ";\n\n")
target.write(" private final String value;\n\n")

target.write ("""\
private ${dataType.type}(String value) {
this.value = value;
}

""")

target.write("""\
@JsonValue
public String getValue() {
return this.value;
}

""")

target.write("""\
@JsonCreator
public static ${dataType.type} fromValue(String value) {
for (${dataType.type} val: ${dataType.type}.values()) {
if (val.value.equals(value)) {
return val;
}
}
throw new IllegalArgumentException(value);
}

""")

target.write ("}\n")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,48 @@ class Identifier {
sb.toString ()
}

/**
* converts a Json string as defined by http://www.json.org/ to a valid (upper case) java
* enum identifier. One way, ie it is not reversible.
*
* conversion rules:
* characters that are not valid java identifiers will be removed. The characters " ", "_",
* "-" (valid or not) are interpreted as word separators and are replaced by "_" and the words
* are converted to upper case.
*
* @param json a valid json "string"
*
* @return a valid upper case enum java identifier
*/
static String toEnum (String json) {
def sb = new StringBuilder()

def wordSplit = false
json.toCharArray ().eachWithIndex { char c, int idx ->

def cu = c.toUpperCase ()
if (idx == 0) {
if (isValidStart (c)) {
sb.append (cu)
}
} else {
if (isValidPart (c)) {
if (wordSplit) {
sb.append ("_")
sb.append (cu)
wordSplit = false
} else {
sb.append (cu)
}
} else {
wordSplit = true
}
}
}

sb.toString ()
}

private static boolean isValidStart (char c) {
Character.isJavaIdentifierStart (c) && !isWordSplitPart (c)
}
Expand Down
Loading