Ant脚本:build.xml
<?xml version="1.0"?>
<project basedir="." default="full">
<property name="projectname" value="test" />
<property name="targetfile" value="xsd/test/test-*.xsd" />
<import file="../../jibx_common.xml" />
<target name="clean">
<delete quiet="true" dir="${basedir}/bin/${projectname}"/>
<delete quiet="true" dir="${basedir}/gen/src/${projectname}"/>
</target>
<target name="codegen" depends="check-runtime,clean">
<echo message="Running code generation from schema"/>
<delete quiet="true" dir="${basedir}/gen/src/${projectname}"/>
<java classname="org.jibx.schema.codegen.CodeGen" fork="yes" classpathref="classpath" failοnerrοr="true">
<arg value="-t"/>
<arg value="${basedir}/gen/src/${projectname}"/>
<!--
<arg value="-b"/>
<arg value="${basedir}/binding.xml"/>
<arg value="-c"/>
<arg value="${basedir}/custom1.xml"/>
<arg value="-u"/>
<arg value="http://www.opentravel.org/OTA/2003/05"/>
-->
<arg value="-n"/>
<arg value="com.99bill.schema.test"/>
<arg value="${targetfile}"/>
</java>
</target>
<!-- compile the classes -->
<target name="compile" depends="check-runtime">
<echo message="Compiling Java source code"/>
<delete quiet="true" dir="${basedir}/bin/${projectname}"/>
<mkdir dir="${basedir}/bin/${projectname}/classes"/>
<javac srcdir="${basedir}/gen/src/${projectname}" destdir="${basedir}/bin/${projectname}/classes" debug="on">
<classpath refid="classpath"/>
</javac>
</target>
<target name="delete">
<echo message="Delete all files excludes *.class..."/>
<delete quiet="true" verbose="true">
<fileset dir="${basedir}/bin/${projectname}/classes" excludes="**/*.class" />
</delete>
</target>
<!-- bind as a separate step -->
<target name="bind" depends="check-binding">
<echo message="Running JiBX binding compiler"/>
<bind binding="${basedir}/gen/src/${projectname}/binding.xml">
<classpath>
<pathelement location="${basedir}/bin/${projectname}/classes"/>
</classpath>
</bind>
</target>
<target name="jar">
<jar destfile="bin/lib/${projectname}.jar" basedir="${basedir}/bin/${projectname}/classes"></jar>
</target>
<!-- run the included test program to read and then write to separate file -->
<target name="run" depends="check-runtime">
<echo message="Running the sample application..."/>
<javac srcdir="${basedir}/src" destdir="${basedir}/bin" debug="on">
<classpath refid="classpath"/>
<classpath>
<pathelement location="bin/lib/${projectname}.jar"/>
</classpath>
</javac>
<java classname="org.jibx.starter.Test" fork="true" failοnerrοr="true">
<classpath refid="classpath"/>
<classpath>
<pathelement location="bin/lib/${projectname}.jar"/>
</classpath>
<arg value="${basedir}/data/data-response.xml"/>
<arg value="${basedir}/out.xml"/>
</java>
</target>
<!-- compile, generate, compile binding, run test -->
<target name="full" depends="codegen,compile,bind,delete,jar,run"/>
</project>
---------------------------------jibx_common.xml
<?xml version="1.0"?>
<project basedir="." default="help">
<property name="jibx-home" value="F:/schmtmp/Projects/JiBXPlugin"/>
<property environment="env"/>
<condition property="jibx-home" value="${env.JIBX_HOME}">
<and>
<not>
<isset property="jibx-home"/>
</not>
<available file="${env.JIBX_HOME}/lib"/>
</and>
</condition>
<!-- make sure required jars are present -->
<condition property="runtime-jars-found">
<available file="${jibx-home}/lib/jibx-run.jar"/>
</condition>
<condition property="binding-jars-found">
<and>
<available file="${jibx-home}/lib/bcel.jar"/>
<available file="${jibx-home}/lib/jibx-bind.jar"/>
<available file="${jibx-home}/lib/jibx-run.jar"/>
</and>
</condition>
<available property="extras-jar-found" file="${jibx-home}/lib/jibx-extras.jar"/>
<!-- set classpath for compiling and running application with JiBX -->
<path id="classpath">
<pathelement location="."/>
<fileset dir="${jibx-home}/lib" includes="*.jar"/>
<pathelement location="bin"/>
</path>
<!-- make sure runtime jars are present -->
<target name="check-runtime">
<fail unless="jibx-home">JiBX home directory not found - define JIBX_HOME system property or set path directly in build.xml file.</fail>
<fail unless="runtime-jars-found">Required JiBX runtime jar jibx-run.jar was not found in JiBX home lib directory (${jibx-home}/lib)</fail>
</target>
<target name="check-binding" depends="check-runtime">
<fail unless="binding-jars-found">Required JiBX binding jar jibx-bind.jar and bcel.jar was not found in JiBX home lib directory (${jibx-home}/lib)</fail>
</target>
<target name="check-extras" depends="check-runtime">
<fail unless="extras-jar-found">Required JiBX extras jar jibx-extras.jar was not found in JiBX home lib directory (${jibx-home}/lib)</fail>
</target>
<!-- binding task definition -->
<taskdef name="bind" classname="org.jibx.binding.ant.CompileTask">
<classpath>
<fileset dir="${jibx-home}/lib" includes="*.jar"/>
</classpath>
</taskdef>
</project>
-------------------------------------------------------------------
Java类代码
public class SpringWSClient extends WebServiceGatewaySupport {
public String send(String requestXML) throws IOException {
getWebServiceTemplate().setMessageFactory(new AxiomSoapMessageFactory());
Resource request = new ByteArrayResource(requestXML.getBytes());
Source requestSource = new ResourceSource(request);
StringResult result = new StringResult();
getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, result);
return result.toString();
}
public static void main(String[] args) throws Exception {
SpringWSClient dp = new SpringWSClient();
dp.setDefaultUri("http://localhost:88/test-springws/services");
String xml =
"<?xml version=/"1.0/" encoding=/"UTF-8/"?><test:test-request xmlns:test=/"http://www.99bill.com/schema/test/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xsi:schemaLocation=/"http://www.99bill.com/schema/test test-request.xsd /"> <test:request-header> <test:service>webservice.customer</test:service><test:version>1.0</test:version><test:method>createCustomer</test:method> </test:request-header> <test:request-body> <test:customer-no>0</test:customer-no> <test:first-name>John</test:first-name> <test:last-name>Smith</test:last-name> <test:phone>test:phone</test:phone> </test:request-body></test:test-request>";
System.out.println("=========" + dp.send(xml));
xml = "<?xml version=/"1.0/" encoding=/"UTF-8/"?><test:test-request xmlns:test=/"http://www.99bill.com/schema/test/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xsi:schemaLocation=/"http://www.99bill.com/schema/test test-request.xsd /"> <test:request-header> <test:service>webservice.customer</test:service><test:version>1.0</test:version><test:method>deleteCustomer</test:method> </test:request-header> <test:request-body> <test:customer-no>0</test:customer-no> <test:first-name>John</test:first-name> <test:last-name>Smith</test:last-name> <test:phone>test:phone</test:phone> </test:request-body></test:test-request>";
System.out.println("=========" + dp.send(xml));
}
}
--------------------------
public class BeanMethodDescriptor {
private Object bean = null;
private Method method = null;
public BeanMethodDescriptor(Method method) {
this.method = method;
}
public Object getBean() {
return bean;
}
public void setBean(Object bean) {
this.bean = bean;
}
public Method getMethod() {
return method;
}
public Class<?> getParameterType() {
return method.getParameterTypes()[0];
}
public Class<?> getReturnType() {
return method.getReturnType();
}
}
-----------------------------
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WebMethod {
String oxm() default "jaxb";
}
---------------------------------------------------------
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebService {
String service();
String version() default "1.0";
}
-------------------------------------------------------------
@JavaSource(created = "2010-07-01", descript = "系统启动时往EndPoint注入信息")
public class WebMethodPostProcessor extends ApplicationObjectSupport implements BeanPostProcessor {
private final Log log = LogFactory.getLog(WebMethodPostProcessor.class);
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass().isAnnotationPresent(WebService.class)) {
log.info("Bean '" + beanName + "' created: " + bean.toString());
SpringWebServiceEndPoint endPoint = (SpringWebServiceEndPoint) this.getApplicationContext().getBean("defaultEndpoint");
this.processBeanMethod(bean, endPoint.getServiceMap());
}
return bean;
}
private void processBeanMethod(Object bean, Map<String, Map<String, BeanMethodDescriptor>> moduleMap) {
WebService service = bean.getClass().getAnnotation(WebService.class);
String key = service.service()+"@"+service.version();
Map<String, BeanMethodDescriptor> methodMap = new HashMap<String, BeanMethodDescriptor>();
Method[] methods = bean.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(WebMethod.class)) {
BeanMethodDescriptor descriptor = new BeanMethodDescriptor(method);
descriptor.setBean(bean);
methodMap.put(method.getName(), descriptor);
}
}
moduleMap.put(key, methodMap);
}
}
-----------------------------------------------------------------------
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="error-response")
@XmlType(name = "error-response")
public class WebServiceErrorResponse {
@XmlElement(name = "version", required = true)
private String version ;
@XmlElement(name = "no", required = true)
private String module;
@XmlElement(name = "error", required = true)
private String error;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
--------------------------------------------------------------------------
@JavaSource(created = "2010-07-01", descript = "WebService服务端,这里做分发")
public class SpringWebServiceEndPoint extends AbstractDom4jPayloadEndpoint {
private final Log log = LogFactory.getLog(SpringWebServiceEndPoint.class);
private final String serviceXPath = "//s:service";
private final String versionXPath = "//s:version";
private final String methodXpath = "//s:method";
private String oxm = BindXmlUtil.OXM_JAXB;
private final Map<String, Map<String, BeanMethodDescriptor>> serviceMap = new HashMap<String, Map<String, BeanMethodDescriptor>>();
public Map<String, Map<String, BeanMethodDescriptor>> getServiceMap() {
return serviceMap;
}
@Override
protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception {
log.debug("request = " + requestElement.asXML());
log.debug("mapping = " + serviceMap);
Map<String, String> xpathMap = new HashMap<String, String>();
xpathMap.put("s", requestElement.getNamespaceURI());
XPath xpathVersion = requestElement.getDocument().createXPath(versionXPath);
XPath xpathService = requestElement.getDocument().createXPath(serviceXPath);
XPath xpathMethod = requestElement.getDocument().createXPath(methodXpath);
xpathVersion.setNamespaceURIs(xpathMap);
xpathService.setNamespaceURIs(xpathMap);
xpathMethod.setNamespaceURIs(xpathMap);
StringBuffer errmsg = new StringBuffer();
String result = "";
String service = xpathService.selectSingleNode(requestElement.getDocument()).getText();
if (service == null){
errmsg.append("module can't be null./n");
}
String version = xpathVersion.selectSingleNode(requestElement.getDocument()).getText();
service = service+"@"+version;
String method = xpathMethod.selectSingleNode(requestElement.getDocument()).getText();
if (method == null){
errmsg.append("method can't be null./n");
}
log.debug("service:" + service + ", method:" + method);
if (errmsg.length() > 0) {
result = getError(errmsg.toString(), service, method);
} else {
BeanMethodDescriptor invocation = null;
if (serviceMap.get(service) != null) {
invocation = serviceMap.get(service).get(method);
}
if (invocation == null) {
result = getError("Can't process you request now! Please wait a minite and retry.", service, method);
} else {
result = this.invoke(invocation, requestElement.asXML());
}
log.info("result = " + result);
}
SAXReader reader = new SAXReader();
responseDocument = reader.read(new ByteArrayInputStream(result.getBytes("UTF-8")));
return responseDocument.getRootElement();
}
private String getError(String errmsg, String module, String version) throws Exception {
WebServiceErrorResponse error = new WebServiceErrorResponse();
error.setVersion(version);
error.setModule(module);
error.setError(errmsg);
return BindXmlUtil.object2Xml(error, oxm);
}
private String invoke(BeanMethodDescriptor methodDesc, String xml) throws Exception {
try {
Class<?> parameterType = methodDesc.getParameterType();
Object parameter = BindXmlUtil.xml2Object(parameterType, xml, oxm);
Object response = methodDesc.getMethod().invoke(methodDesc.getBean(), parameter);
return BindXmlUtil.object2Xml(response, oxm);
} catch (Throwable t) {
t.printStackTrace();
throw new Exception(t);
}
}
public String getOxm() {
return oxm;
}
public void setOxm(String oxm) {
this.oxm = oxm;
}
}
--------------------------------------------------------------------------
@WebService(service="webservice.customer", version="1.0")
public class CustomerWebService{
@WebMethod
public TestResponse createCustomer(TestRequest request) throws JiBXException {
Person person = new Person();
person.setCustomerNo(request.getRequestBody().getCustomerNo());
person.setFirstName(request.getRequestBody().getFirstName());
person.setLastName(request.getRequestBody().getLastName());
Customer customer = new Customer();
customer.setPerson(person);
customer.setStreet("Street");
customer.setCity("city");
customer.setState("state");
customer.setPhone("phone");
customer.setZip(new BigInteger("12354"));
TestResponse response = new TestResponse();
response.setTestResponse(customer);
return response;
}
@WebMethod
public TestResponse deleteCustomer(TestRequest request) throws JiBXException {
System.out.println("delete one customer!");
return new TestResponse();
}
}
-----------------------------------------------------------------------
public class BindXmlUtil {
public final static String OXM_JAXB = "jaxb";
public final static String OXM_JiBX = "jibx";
public static final ConcurrentMap<String,JAXBContext> jaxbCacheMap = new ConcurrentHashMap<String, JAXBContext>();
public static final ConcurrentMap<String,IBindingFactory> jixbCacheMap = new ConcurrentHashMap<String, IBindingFactory>();
/**
* 将xml转换为对象.
* @param <T> 要转换的类型
* @param type 要转换的类型
* @param xml 需要转换的xml
* @return 转换好的结果
* @throws JiBXException
*/
public static <T> T xml2Object(Class<T> type,String xml, String oxm) throws Exception{
StringReader reader = new StringReader(xml);
if (OXM_JiBX.equals(oxm)){
IUnmarshallingContext context = getJiBXBindFactory(type).createUnmarshallingContext();
return (T) context.unmarshalDocument(reader);
}else{
JAXBContext jaxbContext = getJAXBContext(type);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (T) unmarshaller.unmarshal(reader);
}
}
/**
* 把对象转换为xml。
* @param <T> 要转换的对象的类型
* @param object 转换的对象
* @return 转换后的结果
* @throws JiBXException
*/
public static <T> String object2Xml(T object, String oxm) throws Exception{
StringWriter sw = new StringWriter();
if (OXM_JiBX.equals(oxm)){
IMarshallingContext context = getJiBXBindFactory(object.getClass()).createMarshallingContext();
context.setOutput(sw);
context.marshalDocument(object);
}else if (OXM_JAXB.equals(oxm)){
JAXBContext jaxbContext = getJAXBContext(object.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(object, sw);
}
return sw.toString();
}
private static IBindingFactory getJiBXBindFactory(Class<?> clazz) throws JiBXException{
String className = clazz.getName();
IBindingFactory bindingFactory = null;
synchronized (jixbCacheMap) {
if (jixbCacheMap.containsKey(className)) {
bindingFactory = jixbCacheMap.get(className);
} else {
bindingFactory = BindingDirectory.getFactory(clazz);
jixbCacheMap.put(className, bindingFactory);
}
}
return bindingFactory;
}
private static JAXBContext getJAXBContext(Class<?> clazz) throws JAXBException {
String className = clazz.getName();
JAXBContext jaxbContext;
synchronized (jaxbCacheMap) {
if (jaxbCacheMap.containsKey(className)) {
jaxbContext = jaxbCacheMap.get(className);
} else {
jaxbContext = JAXBContext.newInstance(clazz);
jaxbCacheMap.put(className, jaxbContext);
}
}
return jaxbContext;
}
}