Java cxf codegen插件不符合cxf ValidationFeature
根据,为了进行验证,操作输入和输出绑定必须用Java cxf codegen插件不符合cxf ValidationFeature,java,web-services,validation,cxf,Java,Web Services,Validation,Cxf,根据,为了进行验证,操作输入和输出绑定必须用@Valid 但是,由cxf codegen插件生成的webservice接口没有这些注释,而且我似乎找不到允许添加这些注释的命令行参数或插件 @Valid注释不能在不违反Liskov替换原则的情况下放在webservice接口的实现中:在这种情况下,JSR-349(Hibernate Validator)的参考实现会产生HV000151:重写另一个方法的方法不得更改参数约束配置 package org.example.test.configurati
@Valid
但是,由cxf codegen插件生成的webservice接口没有这些注释,而且我似乎找不到允许添加这些注释的命令行参数或插件
@Valid
注释不能在不违反Liskov替换原则的情况下放在webservice接口的实现中:在这种情况下,JSR-349(Hibernate Validator)的参考实现会产生HV000151:重写另一个方法的方法不得更改参数约束配置
package org.example.test.configuration;
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.apache.cxf.validation.BeanValidationFeature;
import org.example.test.services.TestWSImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml", "classpath:META-INF/cxf/cxf-servlet.xml" })
@ComponentScan({ "org.example.test" })
public class ApplicationConfiguration {
@Autowired
private Bus cxfBus;
@Bean
public Endpoint testWSEndpoint() {
EndpointImpl endpoint = new EndpointImpl(cxfBus, new TestWSImpl());
endpoint.setAddress("/testws");
endpoint.publish();
return endpoint;
}
@Bean
public ServletRegistrationBean cxfServlet() {
ServletRegistrationBean servlet = new ServletRegistrationBean(new CXFServlet(), "/services/*");
servlet.setLoadOnStartup(1);
return servlet;
}
@Bean
public Feature validationFeature() {
Feature validationFeature = new BeanValidationFeature();
validationFeature.initialize(cxfBus);
cxfBus.getFeatures().add(validationFeature);
ConstraintViolationInterceptor interceptor = new ConstraintViolationInterceptor();
cxfBus.getInFaultInterceptors().add(interceptor);
cxfBus.getOutFaultInterceptors().add(interceptor);
cxfBus.getProperties().put("exceptionMessageCauseEnabled", true);
return validationFeature;
}
}
package org.example.test.configuration;
import java.text.MessageFormat;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolationException;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.binding.soap.interceptor.Soap11FaultOutInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
public class ConstraintViolationInterceptor extends AbstractSoapInterceptor {
public ConstraintViolationInterceptor() {
super(Phase.MARSHAL);
getBefore().add(Soap11FaultOutInterceptor.class.getName());
}
private static final String TEMPLATE = "[{0}] {1} : {2}";
@Override
public void handleMessage(SoapMessage message) throws Fault {
Fault fault = (Fault) message.getContent(Exception.class);
Throwable exception = fault.getCause();
if (exception instanceof ConstraintViolationException) {
fault.setMessage(processConstraints((ConstraintViolationException) exception));
}
}
private String processConstraints(ConstraintViolationException exception) {
return exception.getConstraintViolations().stream().map((error) -> {
return MessageFormat.format(TEMPLATE, error.getPropertyPath(), error.getMessage(), error.getInvalidValue());
}).collect(Collectors.joining(System.lineSeparator()));
}
}
问题:有人知道用@Valid
注释cxf生成的webservice接口方法参数的方法吗
我知道的存在,但这似乎不是一个容易完成的任务。
最简单的解决方案可能是手动将@Valid
注释添加到webservice界面,但我不习惯修改生成的代码
示例
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example.www</groupId>
<artifactId>webservice-test-bval</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Test bean validation on web service</name>
<properties>
<org.springframework.boot.version>1.4.2.RELEASE</org.springframework.boot.version>
<com.github.krasa.krasa-jaxb-tools>1.5</com.github.krasa.krasa-jaxb-tools>
<org.apache.cxf.version>3.1.3</org.apache.cxf.version>
<cxf-codegen-plugin.version>3.0.1</cxf-codegen-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${org.springframework.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- CXF dependencies -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${org.apache.cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${org.apache.cxf.version}</version>
</dependency>
<!-- Schema validation -->
<dependency>
<groupId>com.github.krasa</groupId>
<artifactId>krasa-jaxb-tools</artifactId>
<version>${com.github.krasa.krasa-jaxb-tools}</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${org.springframework.boot.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf-codegen-plugin.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${project.basedir}/src/main/resources/wsdl/test.wsdl</wsdl>
<wsdlLocation>classpath:wsdl/test.wsdl</wsdlLocation>
<extraargs>
<extraarg>-xjc-XJsr303Annotations</extraarg>
</extraargs>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.github.krasa</groupId>
<artifactId>krasa-jaxb-tools</artifactId>
<version>${com.github.krasa.krasa-jaxb-tools}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
org.example.test.configuration
package org.example.test.configuration;
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.apache.cxf.validation.BeanValidationFeature;
import org.example.test.services.TestWSImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml", "classpath:META-INF/cxf/cxf-servlet.xml" })
@ComponentScan({ "org.example.test" })
public class ApplicationConfiguration {
@Autowired
private Bus cxfBus;
@Bean
public Endpoint testWSEndpoint() {
EndpointImpl endpoint = new EndpointImpl(cxfBus, new TestWSImpl());
endpoint.setAddress("/testws");
endpoint.publish();
return endpoint;
}
@Bean
public ServletRegistrationBean cxfServlet() {
ServletRegistrationBean servlet = new ServletRegistrationBean(new CXFServlet(), "/services/*");
servlet.setLoadOnStartup(1);
return servlet;
}
@Bean
public Feature validationFeature() {
Feature validationFeature = new BeanValidationFeature();
validationFeature.initialize(cxfBus);
cxfBus.getFeatures().add(validationFeature);
ConstraintViolationInterceptor interceptor = new ConstraintViolationInterceptor();
cxfBus.getInFaultInterceptors().add(interceptor);
cxfBus.getOutFaultInterceptors().add(interceptor);
cxfBus.getProperties().put("exceptionMessageCauseEnabled", true);
return validationFeature;
}
}
package org.example.test.configuration;
import java.text.MessageFormat;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolationException;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.binding.soap.interceptor.Soap11FaultOutInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
public class ConstraintViolationInterceptor extends AbstractSoapInterceptor {
public ConstraintViolationInterceptor() {
super(Phase.MARSHAL);
getBefore().add(Soap11FaultOutInterceptor.class.getName());
}
private static final String TEMPLATE = "[{0}] {1} : {2}";
@Override
public void handleMessage(SoapMessage message) throws Fault {
Fault fault = (Fault) message.getContent(Exception.class);
Throwable exception = fault.getCause();
if (exception instanceof ConstraintViolationException) {
fault.setMessage(processConstraints((ConstraintViolationException) exception));
}
}
private String processConstraints(ConstraintViolationException exception) {
return exception.getConstraintViolations().stream().map((error) -> {
return MessageFormat.format(TEMPLATE, error.getPropertyPath(), error.getMessage(), error.getInvalidValue());
}).collect(Collectors.joining(System.lineSeparator()));
}
}
org.example.test.services
package org.example.test.services;
import javax.jws.WebService;
import org.example.test.NewOperation;
import org.example.test.NewOperationResponse;
import org.example.test.ObjectFactory;
import org.example.test.TestWS;
@WebService(endpointInterface = "org.example.test.TestWS", portName = "TestWSPort", serviceName = "TestWS", targetNamespace = "http://www.example.org/test/")
public class TestWSImpl implements TestWS {
@Override
public NewOperationResponse newOperation(NewOperation parameters) {
int in = parameters.getIn();
NewOperationResponse response = new ObjectFactory().createNewOperationResponse();
if (in < 10 || in > 20) {
response.setOut("no no no");
} else {
response.setOut("OK");
}
return response;
}
}
package org.example.test.services;
导入javax.jws.WebService;
导入org.example.test.NewOperation;
导入org.example.test.NewOperationResponse;
导入org.example.test.ObjectFactory;
导入org.example.test.TestWS;
@WebService(endpointInterface=“org.example.test.TestWS”,portName=“TestWSPort”,serviceName=“TestWS”,targetNamespace=”http://www.example.org/test/")
公共类TestWSImpl实现TestWS{
@凌驾
public newOperation响应newOperation(newOperation参数){
int in=parameters.getIn();
NewOperationResponse=newObjectFactory().createNewOperationResponse();
如果(in<10 | in>20){
答复。出发(“否”);
}否则{
答复。出发(“确定”);
}
返回响应;
}
}
参考上面的项目,您可以测试只要
TestWSImpl实现TestWS
(生成的类)就不会发生验证,但是如果TestWSImpl实现TestWSValid
(包含添加了@Valid
的生成代码的类)然后验证工作如预期的那样Apache CXF的wsdl2java支持是可插入的。有一个META-INF/tools-plugin.xml描述符,允许您定义自定义生成器(“前端配置文件”)。因此,如果您在所有cxf生成的webservice接口上都需要一个@有效的注释,您只需插入一个自定义SEIGenerator
。
ApacheCXF使用Velocity模板生成SEI接口。因此,您只需要用自定义模板覆盖默认模板
因此,您不必使用Anox或Krasa,只需创建一个简单的cxf codegen插件
overwrite即可
因此,让我们创建一个单独的项目,您仍然可以将它放在同一个项目中,但放在不同的模块中,但是为了更好的重用性,我会说是一个新项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>org.example.test</groupId>
<artifactId>valid-cxf</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${org.apache.cxf.version}</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="utf-8"?>
<plugin xmlns="http://cxf.apache.org/tools/plugin" name="play" version="" provider="play.typesafe.com">
<frontend name="sample" package="org.apache.cxf.tools.wsdlto.frontend.jaxws" profile="JAXWSProfile">
<container name="JAXWSContainer" package="org.apache.cxf.tools.wsdlto.frontend.jaxws" toolspec="jaxws-toolspec.xml"/>
<processor name="WSDLToJavaProcessor" package="org.apache.cxf.tools.wsdlto.frontend.jaxws.processor"/>
<builder name="JAXWSDefinitionBuilder" package="org.apache.cxf.tools.wsdlto.frontend.jaxws.wsdl11"/>
<generators package="com.example.plugin">
<generator name="CustomSEIGenerator"/>
</generators>
</frontend>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf-codegen-plugin.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${project.basedir}/src/main/resources/wsdl/test.wsdl</wsdl>
<wsdlLocation>classpath:wsdl/test.wsdl</wsdlLocation>
</wsdlOption>
<extraargs>
<extraarg>-fe</extraarg>
<extraarg>sample</extraarg>
</extraargs>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.example.test</groupId>
<artifactId>valid-cxf</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
最后,让我们创建CustomSEIGenerator
,它将使用我们的velocity模板
package org.example.test;
import org.apache.cxf.tools.common.ToolException;
import org.apache.cxf.tools.wsdlto.frontend.jaxws.generators.SEIGenerator;
import java.io.Writer;
/**
* Just a sample custom generator which use custom velocity template to generate SEI
*
*/
public class CustomSEIGenerator extends SEIGenerator {
@Override
protected void doWrite(String templateName, Writer outputs) throws ToolException {
if (templateName.endsWith("/sei.vm")) {
templateName = "valid-sei.vm";
}
super.doWrite(templateName, outputs);
}
}
假设您已经构建了插件覆盖并发布到本地maven repo,接下来您只需要将依赖项信息添加到您的项目pom.xml
。
因此,问题中的pom将保持不变,只有cxf codegen插件
将获得新的依赖项
在pom.xml文件中
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>org.example.test</groupId>
<artifactId>valid-cxf</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${org.apache.cxf.version}</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="utf-8"?>
<plugin xmlns="http://cxf.apache.org/tools/plugin" name="play" version="" provider="play.typesafe.com">
<frontend name="sample" package="org.apache.cxf.tools.wsdlto.frontend.jaxws" profile="JAXWSProfile">
<container name="JAXWSContainer" package="org.apache.cxf.tools.wsdlto.frontend.jaxws" toolspec="jaxws-toolspec.xml"/>
<processor name="WSDLToJavaProcessor" package="org.apache.cxf.tools.wsdlto.frontend.jaxws.processor"/>
<builder name="JAXWSDefinitionBuilder" package="org.apache.cxf.tools.wsdlto.frontend.jaxws.wsdl11"/>
<generators package="com.example.plugin">
<generator name="CustomSEIGenerator"/>
</generators>
</frontend>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf-codegen-plugin.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${project.basedir}/src/main/resources/wsdl/test.wsdl</wsdl>
<wsdlLocation>classpath:wsdl/test.wsdl</wsdlLocation>
</wsdlOption>
<extraargs>
<extraarg>-fe</extraarg>
<extraarg>sample</extraarg>
</extraargs>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.example.test</groupId>
<artifactId>valid-cxf</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
org.apache.cxf
为了记录在案,以下是我认为最适合CustomSEIGenerator实施的内容:
package org.example.test;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.xml.namespace.QName;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.common.ToolException;
import org.apache.cxf.tools.common.model.JAnnotation;
import org.apache.cxf.tools.common.model.JavaInterface;
import org.apache.cxf.tools.common.model.JavaMethod;
import org.apache.cxf.tools.common.model.JavaModel;
import org.apache.cxf.tools.common.model.JavaParameter;
import org.apache.cxf.tools.wsdlto.frontend.jaxws.generators.SEIGenerator;
import org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.WSDLToJavaProcessor;
public class CustomSEIGenerator extends SEIGenerator {
private static final String VALID_PARAM = "VALID_PARAM";
private static final String VALID_RETURN = "VALID_RETURN";
@Override
public void generate(ToolContext penv) throws ToolException {
JAnnotation validAnno = new JAnnotation(Valid.class);
Map<QName, JavaModel> map = CastUtils.cast((Map<?, ?>) penv.get(WSDLToJavaProcessor.MODEL_MAP));
for (JavaModel javaModel : map.values()) {
Map<String, JavaInterface> interfaces = javaModel.getInterfaces();
for (JavaInterface intf : interfaces.values()) {
intf.addImport(Valid.class.getCanonicalName());
List<JavaMethod> methods = intf.getMethods();
for (JavaMethod method : methods) {
List<JavaParameter> parameters = method.getParameters();
method.addAnnotation(VALID_RETURN, validAnno);
for (JavaParameter param : parameters) {
param.addAnnotation(VALID_PARAM, validAnno);
}
}
}
}
super.generate(penv);
}
}
package org.example.test;
导入java.util.List;
导入java.util.Map;
导入javax.validation.Valid;
导入javax.xml.namespace.QName;
导入org.apache.cxf.helpers.CastUtils;
导入org.apache.cxf.tools.common.ToolContext;
导入org.apache.cxf.tools.common.toolsexception;
导入org.apache.cxf.tools.common.model.JAnnotation;
导入org.apache.cxf.tools.common.model.JavaInterface;
导入org.apache.cxf.tools.common.model.JavaMethod;
导入org.apache.cxf.tools.common.model.JavaModel;
导入org.apache.cxf.tools.common.model.JavaParameter;
导入org.apache.cxf.tools.wsdlto.frontend.jaxws.generators.seigerator;
导入org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.WSDLToJavaProcessor;
公共类CustomSEIGenerator扩展了SEIGenerator{
私有静态最终字符串VALID_PARAM=“VALID_PARAM”;
私有静态最终字符串VALID\u RETURN=“VALID\u RETURN”;
@凌驾
公共void generate(ToolContext penv)引发ToolException{
JAnnotation validAnno=新JAnnotation(Valid.class);
Map Map=CastUtils.cast((Map)penv.get(WSDLToJavaProcessor.MODEL_Map));
for(JavaModel-JavaModel:map.values()){
Map interfaces=javaModel.getInterfaces();
for(JavaInterface intf:interfaces.values()){
addImport(Valid.class.getCanonicalName());
List-methods=intf.getMethods();
for(JavaMethod:methods){
List parameters=method.getParameters();
addAnnotation方法(有效返回,validAnno);
for(JavaParameter参数:参数){
参数addAnnotation(有效参数,validAnno);
}
}
}
}
super.generate(penv);
}
}
我修复了给定tools-plugin.xml中缺少的标记,我确实按照您的描述构建并配置了自定义生成器插件作为依赖项,但我仍然没有看到@Valid注释。您认为我可能缺少什么?基本上,我的示例缺少前端名称参数,该参数需要通过添加-fesample
传递给cxf generator。只要看看更新后的pom.xml.great,它现在确实可以工作了!谢谢你把这一切都放在一起,我太懒了,不能不自己做。我有j