Skip to content

Commit ea1d389

Browse files
committed
need enum identifier names
1 parent 122988c commit ea1d389

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

src/main/groovy/com/github/hauner/openapi/support/Identifier.groovy

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,48 @@ class Identifier {
6363
sb.toString ()
6464
}
6565

66+
/**
67+
* converts a Json string as defined by http://www.json.org/ to a valid (upper case) java
68+
* enum identifier. One way, ie it is not reversible.
69+
*
70+
* conversion rules:
71+
* characters that are not valid java identifiers will be removed. The characters " ", "_",
72+
* "-" (valid or not) are interpreted as word separators and are replaced by "_" and the words
73+
* are converted to upper case.
74+
*
75+
* @param json a valid json "string"
76+
*
77+
* @return a valid upper case enum java identifier
78+
*/
79+
static String toEnum (String json) {
80+
def sb = new StringBuilder()
81+
82+
def wordSplit = false
83+
json.toCharArray ().eachWithIndex { char c, int idx ->
84+
85+
def cu = c.toUpperCase ()
86+
if (idx == 0) {
87+
if (isValidStart (c)) {
88+
sb.append (cu)
89+
}
90+
} else {
91+
if (isValidPart (c)) {
92+
if (wordSplit) {
93+
sb.append ("_")
94+
sb.append (cu)
95+
wordSplit = false
96+
} else {
97+
sb.append (cu)
98+
}
99+
} else {
100+
wordSplit = true
101+
}
102+
}
103+
}
104+
105+
sb.toString ()
106+
}
107+
66108
private static boolean isValidStart (char c) {
67109
Character.isJavaIdentifierStart (c) && !isWordSplitPart (c)
68110
}

src/test/groovy/com/github/hauner/openapi/support/IdentifierSpec.groovy

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,17 @@ class IdentifierSpec extends Specification {
3535
"a_b" | "aB" // underscore is valid but unwanted
3636
}
3737

38+
@Unroll
39+
void "convert json string '#json' to valid java enum identifier '#identifier'" () {
40+
expect:
41+
Identifier.toEnum (json) == identifier
42+
43+
where:
44+
json | identifier
45+
"a" | "A"
46+
"a b" | "A_B" // space is invalid
47+
"a-b" | "A_B" // dash is invalid
48+
"_ab" | "AB" // underscore is valid but unwanted
49+
"a_b" | "A_B" // underscore is valid but unwanted
50+
}
3851
}

0 commit comments

Comments
 (0)