gpt4 book ai didi

java - Opencsv:使用@PreAssignmentValidator 时允许更多自定义错误消息

转载 作者:行者123 更新时间:2023-12-05 03:44:47 30 4
gpt4 key购买 nike

给定这个 bean:

@Data
public class Contact {
@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;

@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[0-9]{10}$")
@CsvBindByName(column = "Phone Number", required = true)
private String phone;
}

CsvToBeanBuilder() 配置如下:

...
final CsvToBean<Contact> beans = new CsvToBeanBuilder<Contact>(
Files.newBufferedReader(csvFilePath, StandardCharsets.UTF_8))
.withType(Contact.class)
.withThrowExceptions(false)
.build();

this.contacts = beans.parse();

beans.getCapturedExceptions().stream().forEach(ex -> System.out.println(ex.getMessage()));
...

如果我给它一个像这样的文件:

Contact First Name,Phone Number
joe1,1234567890
jane,123456789

我(正确地)收到了这些错误消息:

Field userName value "joe1" did not match expected format of ^[A-Za-z]{3,8}$
Field phone value "123456789" did not match expected format of ^[0-9]{10}$

由于我将这些消息传回给用户,我希望错误消息使用 CSV 列名而不是 bean 的字段名,并且如果我可以提供自定义验证消息——可能作为附加字段@PreAssignmentValidator? -- 这样消息看起来像:

Field 'User Name' value "joe1" did not match expected format of '3 - 8 alphabetic characters'
Field 'Phone Number' value "123456789" did not match expected format of '10 digits'

关于如何在不编写一些自定义逻辑来转换这些消息的情况下执行此操作的任何建议/指示?

谢谢!


根据@andrewjames 的建议更新了代码

@Getter
public class Contact {
//@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;

//@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[0-9]{10}$")
@CsvBindByName(column = "Phone Number", required = true)
private String phone;

public void setContactFirstName(String contactFirstName) throws CsvValidationException {
if (contactFirstName.length() < 3 || contactFirstName.length() > 8) {
throw new CsvValidationException("'Contact First Name' must be between 3-8 characters long");
}
this.contactFirstName = contactFirstName;
}

public void setPhone(String phone) throws CsvValidationException {
if (phone.length() != 10) {
throw new CsvValidationException("'Phone Number' must be between 10 digits long");
}
this.phone = phone;
}
}

public class ContactTest {
private static final String HEADER = "Contact First Name,Phone Number\n";


@Test
public void test() throws Exception {
String data = HEADER
+ "jo,1234567890\n"
+ "al,123456789"; // This row should generate two exceptions

CsvToBean<Contact> csvToBean = new CsvToBeanBuilder<Contact>(new StringReader(data))
.withType(Contact.class)
.withThrowExceptions(false)
// .withExceptionHandler(new ExceptionHandlerQueue()) // Tried this way after commenting previous line
.build();

List<Contact> beans = csvToBean.parse();

csvToBean.getCapturedExceptions().stream().forEach((ex) -> {
System.out.println((int) ex.getLineNumber() + " -- " + ex.getMessage());
});
}
}

但现在 csvToBean.parse() 只是抛出异常。对于第二行,我只得到第一个异常(exception):

Exception in thread "pool-1-thread-2" java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:111)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
... 3 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:111)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
... 3 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more

java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.

at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.checkExceptions(IntolerantThreadPoolExecutor.java:253)
at com.opencsv.bean.concurrent.LineExecutor.checkExceptions(LineExecutor.java:67)
at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.areMoreResultsAvailable(IntolerantThreadPoolExecutor.java:303)
at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.tryAdvance(IntolerantThreadPoolExecutor.java:313)
at com.opencsv.bean.concurrent.LineExecutor.tryAdvance(LineExecutor.java:24)
at java.base/java.util.Spliterator.forEachRemaining(Spliterator.java:326)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at com.opencsv.bean.CsvToBean.parse(CsvToBean.java:117)
at org.lotia.example.ContactTest.test(ContactTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more


Process finished with exit code 255

最佳答案

如果您不想添加另一个库,您还可以创建一个自定义 validator 来代替 MustMatchRegexExpression:

public class MySpecialMustMatchRegexExpression implements StringValidator {
private String regex = "";


public MustMatchRegexExpression() {
this.regex = "";
}

@Override
public boolean isValid(String value) {
if (regex.isEmpty()) {
return true;
}
return value.matches(regex);
}

@Override
public void validate(String value, BeanField field) throws CsvValidationException {
if (!isValid(value)) {
throw new CsvValidationException(String.format(ResourceBundle.getBundle("mustMatchRegex", field.getErrorLocale())
.getString("validator.regex.mismatch"), field.getDeclaredAnnotations[1], value, regex));
}
}

@Override
public void setParameterString(String value) {
if (value != null && !value.isEmpty()) {
regex = value;
}
}
}

并在您的预赋值 validator 中使用它:

@PreAssignmentValidator(validator = MySpecialMustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;

关于java - Opencsv:使用@PreAssignmentValidator 时允许更多自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66285717/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com