I have a requirement for customizing the JAXB bindings for a SOAP client. I need to impose bindings at specific nodes available in the WSDL. The WSDL schema looks like:
<xs:complexContent mixed="false">
<xs:extension base="q1:RequestBase" xmlns:q1="http://www.epsilon.com/webservices/">
<xs:sequence>
<xs:element minOccurs="0" name="RegisterDate" type="xs:dateTime"/>
</xs:extension>
</xs:complexContent>
I need to apply binding for 'RegisterDate' attribute. I have added the following binding:
parseMethod="com.dunkindonuts.website.loyalty.util.DateAdapter.parseDateTime"
printMethod="com.dunkindonuts.website.loyalty.util.DateAdapter.printDateTime"/>
However, it is not working. When i apply this binding on global level, it works perfectly fine.
Can anyone provide any pointers to resolve this issue?
Regards,
Namit
I can't tell from your original post if your non-global binding included the schema location and/or binding node (xpath)??? something like:
<jxb:bindings schemaLocation="PATH_TO_YOUR_SCHEMA">
<jxb:bindings node="//xs:element[#name='RegisterDate']">
<jxb:property>
<jxb:baseType ...
Related
Whenever i try to create a Webservice from a wsdl url i get an Error window in Netbeans IDE. Where there is no package or reference like this.
Here is my stack trace.
parsing WSDL...
[ERROR] A class/interface with the same name "org.wi.link.action.Exception" is already in use. Use a class customization to resolve this conflict.
line 35 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
[ERROR] (Relevant to above error) another "Exception" is generated from here.
line 30 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 35 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
[ERROR] (Related to above error) This is the other declaration.
line 30 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 38 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
[ERROR] (Related to above error) This is the other declaration.
line 32 of file:/D:/Development/source/WebServiceProject/TestProject/src/conf/xml-resources/web-service-references/service/wsdl/urladdress/wionline/services/service.wsdl
D:\Development\source\WebServiceProject\TestProject\nbproject\jaxws-build.xml:225: wsimport failed
BUILD FAILED (total time: 2 seconds)
I can also post jaxws-build.xml if required Thanks in advance.
Webservice cannot be created with wsdl , only webservice client(to consume WS) can be created using wsdl.
For me the problem solved , by mistake i was adding "Web Service Client" with incorrect wsdl url , i was adding http://localhost:8080/MyService/MyService?Tester, which is the ws tester url.
The correct url should be the WSDL url i.e. http://localhost:8080/MyService/MyService?WSDL
Steps followed:
1. Go to Project-war
2. Right Click New > WebService Client
3. Select WSDL URL, paste the WSDL url , give package name
And its done :)
For me the problem solved .
You can only create WS from scratch or from existing bean.
Hope this will help you.
Under the hood wsimport utinilty uses JAXB compiler, so actualy error is relevant to JAXB. As stated in JAXB guide, you have two options - use schemabindings or factoryMethod customization, though that depends on your WSLD and it might be not possible. Another option would be to rename conflicting types in your WSDL document.
Based on comment below lets assume that this is your schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="Exception">
<xs:sequence>
<xs:element minOccurs="0" name="Exception" nillable="true" type="xs:anyType"/>
</xs:sequence>
</xs:complexType>
<xs:element name="Exception">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="Exception" nillable="true" type="Exception"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
To gernerate same errors you might run xjc compiler:
/bin/xjc.sh schema.xsd
As mentioned above easyest way to fix this issue would be to rename complex type or element name. But to make things more interesting you might define JAXB customization
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="1.0">
<jaxb:bindings schemaLocation="schema.xsd">
<jaxb:bindings node="//xs:complexType[#name='Exception']">
<jaxb:factoryMethod name="TypeException"/>
<jaxb:class name="TypeException" />
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
And try once more:
/bin/xjc.sh -b binding.xml schema.xsd
Same binding might be supplied to wsimport utility:
wsimport myService.wsdl -b binding.xml
I'm trying to validate a really simple xml using xsd, but for some reason I get this error.
I'll really appreciate if someone can explain me why.
XML File
<?xml version="1.0" encoding="utf-8"?>
<MyElement>A</MyElement>
XSD File
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Test"
xmlns:tns="http://www.example.org/Test"
elementFormDefault="qualified">
<simpleType name="MyType">
<restriction base="string"></restriction>
</simpleType>
<element name="MyElement" type="tns:MyType"></element>
</schema>
Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.
You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.
After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs:
https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));
The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:
// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);
DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));
I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.
My initial wrong XSD was alike the following:
<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="XXX" type="XXX_TYPE"/>
</xs:sequence>
</xs:complexType>
The good XSD format for my migration to succeed was the following:
<xs:element name="Document">
<xs:complexType>
<xs:sequence>
<xs:element ref="XXX"/>
</xs:sequence>
</xs:complexType>
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>
And so on for every similar XSD nodes.
I got this same error working in Eclipse with Maven with the additional information
schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.
To expand upon the top answer. If you're using Java Web Services (JAX-WS) annotations to define your services, like in this example:
#WebService(..., targetNamespace = "http://bar.foo.com/")
Then make sure that your SOAP request has exactly the same namespace as defined in your annotation:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:foo="http://bar.foo.com/">
<soapenv:Header/>
<soapenv:Body>
<foo:someRequest>
...
</foo:someRequest>
</soapenv:Body>
</soapenv:Envelope>
The targetNamespace in your annotation and the xmlns:foo property in the XML request must match! Literally every character (including whitespace) must match. Also don't forget to put the / at the end as well (it's a very common mistake).
I am a new comer to JaxB World and I am facing one problem w.r.t. unmarshalling of the stored xml content into java class object. Problem description is as follows. Let me know if this is solvable
I have my xsd file which contains following content(this is just a example)
Student info
<xs:complexType name="specialization" abstract="true">
</xs:complexType>
<xs:complexType name="Engineering">
<xs:complexContent>
<xs:extension base="specialization">
<xs:sequence>
<xs:element name="percentage" type="xs:int" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Medical">
<xs:complexContent>
<xs:extension base="specialization">
<xs:sequence>
<xs:element name="grade" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
Now all the corresponding java classes are generated by compiling the xsd. Now lets assume in my application i will set the specialization attribute of Student info by constructing Engineering class instance. So after all the operation when i save
the xml file that get saved will have the entry like below
<Student>
<Name>Name1</Name>
<Specialization>
<percentage>78<percentage>
</Specialization>
</Student>
Now when the above content goes for unmarshalling, unmarshalling fails saying unexpected element . I guess this is b'cos Specialization element is of type specialization it calls unmarshalling on itself rather than derived object which is stored.
I hope my explanation is clear. Is there any way that we can unmarshall based on derived class instanse type. The xsd and bindings.xjb file is completely in my control so i can add or modify any entries/info which conveys to unmarshalling rules to unmarshall on derived class.
Thanks for your Suggestion but the it still not working for me.
Here is what I tried
Option #1 - xsi:type
My xsd looks same as what is explained in the example but still the Xsi:type doesn't come in the resulted xml. Do i need to add any other setting while compiling? Which JaxB version should i use for this?
Option#2 - Substitution Groups
When i added the substitution entry part in my xsd, XSD compilation failed saying duplicate names "Engineering" and "Medical". I guess element name and type Name being same compilation cribs(All engineering, Medical,specialization being same both in type definition and element Name)
I can't modify the generated classes as we are using Model driven Architecture. Only thing that is in hand is xsd. Any modification to the xsd is allowed. Ideally First option should have worked. But can't figure out why it is not working. Let me know if you have some suggestion to narrow down the problem.
There are different ways of representing Java inheritance in XML when using JAXB:
Option #1 - xsi:type
In this representation an attribute is used to indicate the subtype being used to populate this element.
<Student>
<Name>Name1</Name>
<Specialization xsi:type="Engineering">
<percentage>78<percentage>
</Specialization>
</Student>
For a detailed example see:
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.htmlhtml
Option #2 - Substitution Groups
Here an element name is used to indicate the subtype. This corresponds to the schema concept of substitution groups and leverages JAXB's #XmlElementRef annotation:
<Student>
<Name>Name1</Name>
<Engineering>
<percentage>78<percentage>
</Engineering>
</Student>
For a detailed example see:
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
I am running into JAXB Unmarshalling error as below.
The foo.bar.Base is an abstract class, with an #XmlSeeAlso annotation, which lists foo.bar.SubBase (which is a concrete subclass of foo.bar.Base)
Both of the above classes are statically reachable from a main/entry class: com.example.Request
The JAXBContext is create using the packages string variant viz:
JAXBContext.newInstance("com.example",...);
The above created JAXBContext correctly lists all the three classes : com.example.Request, foo.bar.Base and foo.bar.SubBase as "classes known to this JAXBContext"
But it fails at runtime during the unmarshal call below.. I am unable to figure out what is wrong here.
unmarshaller.unmarshal(<some-DOM-Element-Instance>, com.example.Request.class);
Any pointers will be appreciated!
Thanks!
The stacktrace is:
Caused by: javax.xml.bind.UnmarshalException: Unable to create an instance of foo.bar.Base - with linked exception: [java.lang.InstantiationException]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:642)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:254)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.createInstance(UnmarshallingContext.java:609)
at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.startElement(StructureLoader.java:181)
at com.sun.xml.bind.v2.runtime.unmarshaller.XsiTypeLoader.startElement(XsiTypeLoader.java:76)
at com.sun.xml.bind.v2.runtime.unmarshaller.ProxyLoader.startElement(ProxyLoader.java:55)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:481)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:459)
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:71)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:148)
at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:239)
at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:276)
at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:245)
at com.sun.xml.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:122)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:314)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:293)
Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.sun.xml.bind.v2.ClassFactory.create0(ClassFactory.java:123)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.createInstance(ClassBeanInfoImpl.java:261)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.createInstance(UnmarshallingContext.java:603)
... 69 more
EDIT #Blaise and #Ross
Thank you very much Blaise and Ross for your pointers. I think I should have included the schema that is being worked off, here.
The relevant schema looks like this:
<xs:complexType name="Request">
<xs:sequence>
<xs:element name="selectedBase" form="unqualified" nillable="true" type="xs:anyType" minOccurs="0"/>
<xs:element name="selectedSubBase" form="unqualified" nillable="true" type="ns1:SubBase" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Base">
<xs:sequence>
<xs:element name="ID" form="unqualified" nillable="true" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="SubBase">
<xs:complexContent>
<xs:extension base="ns1:Base">
<xs:sequence>
<xs:element name="subBaseElement" form="unqualified" nillable="true" type="xs:anyType" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
So the schema doesn't have substitution group definition (so I guess #XmlElementRef doesn't apply here, or would it still work?), but is using extension. The payload will be :
<ns:Request>
<selectedBase>123</selectedBase>
<selectedSubBase>
<ID>321</ID>
<subBaseElement>123</subBaseElement>
</selectedSubBase>
</ns:Request>
So , the element in the payload occuring is <selectedSubBase> and not <selectedBase xsi:type="ns:SubBase"/>
So which strategy would apply here?
The #XmlSeeAlso annotation is used as a convenience mechanism to tell your JAXB impl that metadata should also be created for the referenced classes. While it is most often used to specify subclasses it is not a mechanism to configure inheritance relationships.
Since JAXB is attempting to instantiate an instance of the abstract super class (foo.bar.Base), it appears as though your XML message does not contain enough information to specify the correct sub-type to be unmarshalled.
This can be done with the xsi:type attribute:
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html
You can also use substitution groups (#XmlElementRef), where the element name is used to determine the appropriate sub-type:
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
JAXB implementations (such as EclipseLink JAXB (MOXy)), also contain extensions for handling inheritance:
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-moxy-extension.html
And if you would like to ignore the inheritance relationship altogether you can use the #XmlTransient annotation:
http://blog.bdoughan.com/2011/06/ignoring-inheritance-with-xmltransient.html
You need to be using XmlElementRef on the field containing the reference to Base, to tell JAXB that it should look at subclasses. JAXB is clearly trying to instantiate your base class (which it can't do, of course).
Have a look at XmlElementRef's docs.
try #XmlSeeAlso
#XmlSeeAlso({ExchangeFormat.class}) public abstract class MapperJsonXml <T>
#XmlRootElement(name="ExchangeFormat") public class ExchangeFormat extends MapperJsonXml<ExchangeFormat>
it works
Using dom4j DOMDocument to feed validator.validate(DOMSource) fails in java 1.6 (with xsi:noNamespaceSchemaLocation is not allowed to appear in root element), works in 1.5
I'm finding the following problem quite intractable (OK, that's an understatement) - any insights will be appreciated. Currently it seems like the best idea is to drop dom4j in favour of e.g. XOM (http://stackoverflow.com/questions/831865/what-java-xml-library-do-you-recommend-to-replace-dom4j).
I've been validating in memory XML created from dom4j 'new DOMDocument()' - but this will not work with Java 6.
The following call to validate(source) of a dom4j (1.6.1) DOMDocument derived DOMSource works with Java 1.5.x but fails with Java 1.6.x:
public void validate() throws Exception {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setErrorHandler(null);
Schema schemaXSD = schemaFactory.newSchema(new URL(getSchemaURLString()));
Validator validator = schemaXSD.newValidator();
DOMSource source = new DOMSource(getDocument());
validator.validate(source);
}
getSchemaURLString() is also used to add the xsi:noNamespaceSchemaLocation attribute to the root node, i.e.:
xsi:noNamespaceSchemaLocation="http://localhost:8080/integration/xsd/fqlResponseSchema-2.0.xsd"
The exception follows:
Exception: org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'xsi:noNamespaceSchemaLocation' is not allowed to appear in element 'specialfields'.;
complex-type.3.2.2: Attribute 'xsi:noNamespaceSchemaLocation' is not allowed to appear in element 'specialfields'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:417)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3182)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processAttributes(XMLSchemaValidator.java:2659)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2066)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:705)
at com.sun.org.apache.xerces.internal.jaxp.validation.DOMValidatorHelper.beginNode(DOMValidatorHelper.java:273)
at com.sun.org.apache.xerces.internal.jaxp.validation.DOMValidatorHelper.validate(DOMValidatorHelper.java:240)
at com.sun.org.apache.xerces.internal.jaxp.validation.DOMValidatorHelper.validate(DOMValidatorHelper.java:186)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl.validate(ValidatorImpl.java:104)
at javax.xml.validation.Validator.validate(Validator.java:127)
Here's the start of the XML - generated after disabling the call to validator.validate(source):
<?xml version="1.0" encoding="utf-8"?>
<meetings xsi:noNamespaceSchemaLocation="http://localhost:8080/integration/xsd/fqlResponseSchema-2.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
.............
</meetings>
And of the XSD:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="meetings">
<xs:complexType>
<xs:choice>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" ref="summary" />
<xs:element minOccurs="0" maxOccurs="unbounded" ref="meeting" />
</xs:sequence>
<xs:element ref="error" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="summary">
................
So my root element is being rejected because it contains a xsi:noNamespaceSchemaLocation attribute. And the schema itself does not specify that as a valid attribute of my root element?
At this point it seems to me that I need to give up on dom4j for this task and switch to one of the other solutions, for example as outlined here:
But I'd like to know what I've done wrong at any rate!
Thanks in advance.
I had the same issue, and I found the following documentation at
http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi/index.html
Validate against a document-specified schema
Some documents specify the schema they expect to be validated against,
typically using xsi:noNamespaceSchemaLocation and/or
xsi:schemaLocation attributes like this:
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
...
If you create a schema without specifying a URL, file, or source, then
the Java language creates one that looks in the document being
validated to find the schema it should use. For example:
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema();
However, normally this isn't what you want. Usually the document
consumer should choose the schema, not the document producer.
Furthermore, this approach works only for XSD. All other schema
languages require an explicitly specified schema location.
The reason seems to be that non-namespace aware JAXP SAXParser is being created and used (see Link).
And solution for different libs I found at www.edankert.com.