From ec4b06c440bf72ca143d5bb8fb08fde264d3fe33 Mon Sep 17 00:00:00 2001 From: Markus KARG Date: Thu, 14 Dec 2023 15:54:06 +0000 Subject: [PATCH] Fixes #557: Now validates BEFORE conversion --- .../java/com/beust/jcommander/JCommander.java | 12 ++++++----- .../com/beust/jcommander/JCommanderTest.java | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/beust/jcommander/JCommander.java b/src/main/java/com/beust/jcommander/JCommander.java index b257e7ef..d2d47284 100644 --- a/src/main/java/com/beust/jcommander/JCommander.java +++ b/src/main/java/com/beust/jcommander/JCommander.java @@ -795,6 +795,13 @@ else if (commands.isEmpty()) { // initMainParameterValue(arg); String value = a; // If there's a non-quoted version, prefer that one + + for(final Class validator : mainParameter.annotation.validateWith() + ) { + mainParameter.description.validateParameter(validator, + "Default", value); + } + Object convertedValue = value; // Fix @@ -813,11 +820,6 @@ else if (commands.isEmpty()) { } } - for(final Class validator : mainParameter.annotation.validateWith() - ) { - mainParameter.description.validateParameter(validator, - "Default", value); - } mainParameter.description.setAssigned(true); mainParameter.addValue(convertedValue); diff --git a/src/test/java/com/beust/jcommander/JCommanderTest.java b/src/test/java/com/beust/jcommander/JCommanderTest.java index 0edfccc5..f8827774 100644 --- a/src/test/java/com/beust/jcommander/JCommanderTest.java +++ b/src/test/java/com/beust/jcommander/JCommanderTest.java @@ -25,6 +25,7 @@ import com.beust.jcommander.command.CommandMain; import com.beust.jcommander.converters.EnumConverter; import com.beust.jcommander.converters.FileConverter; +import com.beust.jcommander.converters.PathConverter; import com.beust.jcommander.internal.Lists; import com.beust.jcommander.internal.Maps; import org.testng.Assert; @@ -34,6 +35,7 @@ import java.io.*; import java.math.BigDecimal; import java.nio.charset.Charset; +import java.nio.file.Path; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @@ -822,6 +824,25 @@ class A { new JCommander(a).parse("b"); } + static class PathValidator implements IParameterValidator { + @Override + public void validate(String name, String value) throws ParameterException { + if (value.contains("\0")) + throw new ParameterException("this message comes from the validator (not from the converter)"); + } + } + + @Test(expectedExceptions = ParameterException.class, expectedExceptionsMessageRegExp = "this message comes from the validator \\(not from the converter\\)") + public void mainParameterShouldBeValidatedBEFOREConversion() throws Throwable { + class A { + @Parameter(validateWith = PathValidator.class, converter = PathConverter.class) + public Path path; + } + + A a = new A(); + new JCommander(a).parse("invalid\0/path"); + } + @Parameters(commandNames = {"--configure"}) public static class ConfigureArgs { }