Skip to content

Commit 2efb924

Browse files
committed
Fix Version constructor from string
1 parent cb204b2 commit 2efb924

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

leshan-core/src/main/java/org/eclipse/leshan/core/LwM2m.java

+11-6
Original file line numberDiff line numberDiff line change
@@ -144,20 +144,25 @@ public static Version getDefault() {
144144
public static String validate(String version) {
145145
if (version == null || version.isEmpty())
146146
return "version MUST NOT be null or empty";
147-
String[] versionPart = version.split("\\.");
148-
if (versionPart.length != 2) {
147+
// We use split with limit = -1 to be sure "split" will discard trailing empty strings
148+
String[] versionParts = version.split("\\.", -1);
149+
if (versionParts.length != 2) {
149150
return String.format("version (%s) MUST be composed of 2 parts", version);
150151
}
151152
for (int i = 0; i < 2; i++) {
153+
String versionPart = versionParts[i];
152154
try {
153-
short parsedShort = Short.parseShort(versionPart[i]);
155+
if (versionPart.length() > 1 && versionPart.startsWith("0")) {
156+
return String.format("version (%s) part %d (%s) must not be prefixed by 0", version, i + 1,
157+
versionPart);
158+
}
159+
short parsedShort = Short.parseShort(versionPart);
154160
if (parsedShort < 0) {
155161
return String.format("version (%s) part %d (%s) must not be negative", version, i + 1,
156-
versionPart[i]);
162+
versionPart);
157163
}
158164
} catch (Exception e) {
159-
return String.format("version (%s) part %d (%s) is not a valid short", version, i + 1,
160-
versionPart[i]);
165+
return String.format("version (%s) part %d (%s) is not a valid short", version, i + 1, versionPart);
161166
}
162167
}
163168
return null;

leshan-core/src/test/java/org/eclipse/leshan/core/VersionTest.java

+3
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ private static Stream<Arguments> illegal_arguments() {
8585
return Stream.of(args(() -> new Version(null), "version MUST NOT be null or empty"),
8686
args(() -> new Version(""), "version MUST NOT be null or empty"),
8787
args(() -> new Version("foo"), "version (foo) MUST be composed of 2 parts"),
88+
args(() -> new Version("0001.0"), "version (0001.0) part 1 (0001) must not be prefixed by 0"),
89+
args(() -> new Version("1.02"), "version (1.02) part 2 (02) must not be prefixed by 0"),
90+
args(() -> new Version("1.0."), "version (1.0.) MUST be composed of 2 parts"),
8891
args(() -> new Version("1.0.0"), "version (1.0.0) MUST be composed of 2 parts"),
8992
args(() -> new Version("-1.0"), "version (-1.0) part 1 (-1) must not be negative"),
9093
args(() -> new Version("1.-1"), "version (1.-1) part 2 (-1) must not be negative"),

0 commit comments

Comments
 (0)