Skip to content

Commit

Permalink
Fix Version constructor from string
Browse files Browse the repository at this point in the history
  • Loading branch information
sbernard31 committed Nov 8, 2023
1 parent cb204b2 commit 8e7cd35
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
17 changes: 11 additions & 6 deletions leshan-core/src/main/java/org/eclipse/leshan/core/LwM2m.java
Original file line number Diff line number Diff line change
Expand Up @@ -144,20 +144,25 @@ public static Version getDefault() {
public static String validate(String version) {
if (version == null || version.isEmpty())
return "version MUST NOT be null or empty";
String[] versionPart = version.split("\\.");
if (versionPart.length != 2) {
// We use split with limit = -1 to be sure "split" will discard trailing empty strings
String[] versionParts = version.split("\\.", -1);
if (versionParts.length != 2) {
return String.format("version (%s) MUST be composed of 2 parts", version);
}
for (int i = 0; i < 2; i++) {
String versionPart = versionParts[i];
try {
short parsedShort = Short.parseShort(versionPart[i]);
if (versionPart.length() > 1 && versionPart.startsWith("0")) {
return String.format("version (%s) part %d (%s) must not be prefixed by 0", version, i + 1,
versionPart);
}
short parsedShort = Short.parseShort(versionParts[i]);
if (parsedShort < 0) {
return String.format("version (%s) part %d (%s) must not be negative", version, i + 1,
versionPart[i]);
versionPart);
}
} catch (Exception e) {
return String.format("version (%s) part %d (%s) is not a valid short", version, i + 1,
versionPart[i]);
return String.format("version (%s) part %d (%s) is not a valid short", version, i + 1, versionPart);
}
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ private static Stream<Arguments> illegal_arguments() {
return Stream.of(args(() -> new Version(null), "version MUST NOT be null or empty"),
args(() -> new Version(""), "version MUST NOT be null or empty"),
args(() -> new Version("foo"), "version (foo) MUST be composed of 2 parts"),
args(() -> new Version("0001.0"), "version (0001.0) part 1 (0001) must not be prefixed by 0"),
args(() -> new Version("1.02"), "version (1.02) part 2 (02) must not be prefixed by 0"),
args(() -> new Version("1.0."), "version (1.0.) MUST be composed of 2 parts"),
args(() -> new Version("1.0.0"), "version (1.0.0) MUST be composed of 2 parts"),
args(() -> new Version("-1.0"), "version (-1.0) part 1 (-1) must not be negative"),
args(() -> new Version("1.-1"), "version (1.-1) part 2 (-1) must not be negative"),
Expand Down

0 comments on commit 8e7cd35

Please sign in to comment.