给定此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 Numbern";
@Test
public void test() throws Exception {
String data = HEADER
+ "jo,1234567890n"
+ "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 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
如果您不想添加另一个库,您还可以创建一个自定义验证器来代替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;
}
}
}
在赋值前验证器中使用
@PreAssignmentValidator(validator = MySpecialMustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;
Hibernate的验证是在转换后进行的,所以这意味着您必须首先将数据从CSV读取到目标bean的Contact
列表中。
但是您仍然可以以系统的方式捕获所有验证消息,并且您可以自定义它们以满足您的特定需求。
首先你需要一些额外的库:
- Hibernate验证器(及其依赖项)
- Glassfish的EL(表达式语言)处理器
我使用Maven:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
现在您可以从Contact
类中删除@PreAssignmentValidator
注释,并使用这个新的导入:
import javax.validation.constraints.Pattern;
注释:
@Pattern(regexp="^[A-Za-z]{3,8}$",
message="The value '${validatedValue}' in the 'Contact First Name' column did not match the expected format of 3 to 8 letters.")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;
@Pattern(regexp="^[0-9]{10}$", message="Another custom message...")
@CsvBindByName(column = "Phone Number", required = true)
private String phone;
在处理CSV文件时,您的逻辑与原始问题中的逻辑相同。但是,您可以使用Hibernate而不是使用beans.getCapturedExceptions()
。
需要以下导入:
import javax.validation.ValidatorFactory;
import javax.validation.Validator;
import javax.validation.Validation;
import javax.validation.ConstraintViolation;
Hibernate提供了您需要的实现类。
主要逻辑(适用于我的测试用例):
Path csvFilePath = Paths.get("C:/tmp/csv/test_01.csv");
final CsvToBean<Contact> beans = new CsvToBeanBuilder<Contact>(
Files.newBufferedReader(csvFilePath, StandardCharsets.UTF_8))
.withType(Contact.class)
.withThrowExceptions(false)
.build();
List<Contact> contacts = beans.parse();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
for (Contact contact : contacts) {
Set<ConstraintViolation<Contact>> violations = validator.validate(contact);
for (ConstraintViolation<Contact> violation : violations) {
System.out.println(violation.getMessage());
}
}
对于这样的CSV输入行:
joe9,123456789
您将得到以下错误信息打印:
要明确的是,这不是在CSV解析期间发生的,而是在之后的单独步骤中发生的。这是(根据我的经验)Hibernate用于基本验证的典型方式。'联系人姓名'列中的值'joe9'与预期的3到8个字母的格式不匹配。