How to skip a particular empty field from appearing in XML file based on XSD file - xsd

I have an XSD definition as :
<beanio xmlns="http://www.beanio.org/2012/03">
<stream name="udraccess" format="xml">
<parser class="org.beanio.stream.xml.XmlRecordParserFactory" />
.
..lines
..of
..XML code
<segment name="aggregationDimensions" class="java.util.HashMap" collection="list" minOccurs="0" maxOccurs="unbounded">
<segment name="aggregationDimension" class="java.util.HashMap" collection="list" minOccurs="0" maxOccurs="unbounded">
<field name="aggregationDimensionType" xmlType="element" minOccurs="0"/>
<field name="aggregationThresholdDimensionUnitType" xmlType="element" minOccurs="0" />
<field name="aggregationDimensionValue" xmlType="element" minOccurs="0"/>
<segment name="aggregationDimensionAverageInfo" class="java.util.HashMap" collection="list" minOccurs="0" maxOccurs="unbounded">
<field name="averageValueTotal" xmlType="element" minOccurs="0"/>
<field name="averageValueCount" xmlType="element" minOccurs="0"/>
<field name="averageValuePerType" xmlType="element" minOccurs="0"/>
</segment>
</segment>
</segment>
Now in this particular segment: aggregationDimensionAverageInfo, I need that if this value is not present in the input XML, the output XML file should not have that field at all... Currently I am getting the field as an empty array, I want that it should be skipped completely if missing:
"aggregationDimensions": [
{
"aggregationDimension": [
{
"aggregationDimensionAverageInfo": [],
"aggregationDimensionType": "106",
"aggregationDimensionValue": "15:"
}
]
}
],
If that field is present in the input XML, I get it alright as below:
"aggregationDimensions": [
{
"aggregationDimension": [
{
"aggregationDimensionAverageInfo": [
{
"averageValuePerType": "50",
"averageValueTotal": "50",
"averageValueCount": "1"
}
],
"aggregationDimensionType": "106",
"aggregationDimensionValue": "0:15"
}
]
}
],
I need help with the scenario where its missing from the input XML.

You need to set the lazy attribute on the segment to true.
<segment name="aggregationDimensionAverageInfo" lazy="true" class="java.util.HashMap" collection="list" minOccurs="0" maxOccurs="unbounded" >
<field name="averageValueTotal" xmlType="element" minOccurs="0"/>
<field name="averageValueCount" xmlType="element" minOccurs="0"/>
<field name="averageValuePerType" xmlType="element" minOccurs="0"/>
</segment>
The reference guide state the following for the lazy attribute on a segment:
If set to true, the class or collection bound to this segment will
only be instantiated if at least one child attribute is not null or
the empty String. Defaults to false. This functionality differs from
minOccurs in that the fields may still exist in the input stream.

Related

Nodejs SOAP library. Cannot read 'elements' of undefined

I am using soap v0.43.0 to make a soap request to a SOAP service.
I get an error "Cannot read 'elements' of undefined" at node_modules/soap/lib/wsdl/elements.js, when making a soap call.
This WSDL has two operations, SubmitNote & SubmitPromiseToPayNote.
When I comment out everything that pertains to SubmitPromiseToPayNote, my code for SubmitNote works well and I get a response. However, I want both functionalities to work.
//create the client
const clientOptions = {
disableCache: false,
endpoint: notesEndpoint,
escapeXML: false,
preserveWhitespace: true,
httpClient: myX509Client,
request: requestProxy,
};
const client = await soap.createClientAsync(
'src/v1/resources/NoteServiceWSDL.wsdl',
clientOptions,
);
client.addHttpHeader('Content-Type', 'application/soap+xml; charset=utf-8');
//call the operation
const result = await client.SubmitNoteAsync({
_xml: xmlRequest,
});
return result;
This is the WSDL
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions name="BizTalkServiceInstance" targetNamespace="http://VCI.ESB.NoteServiceOnRamp"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex"
xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://VCI.ESB.NoteServiceOnRamp"
xmlns:wsa10="http://www.w3.org/2005/08/addressing"
xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<wsdl:documentation>
<CreationInfo Created="2014-10-14 09:28:00Z"/>
</wsdl:documentation>
<wsp:Policy wsu:Id="WSHttpBinding_ITwoWayAsyncVoid_policy">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding
xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="false"/>
</wsp:Policy>
</sp:TransportToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic256/>
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Strict/>
</wsp:Policy>
</sp:Layout>
</wsp:Policy>
</sp:TransportBinding>
<wsaw:UsingAddressing/>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
<wsdl:types>
<xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/Message"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://schemas.microsoft.com/Message">
<xs:complexType name="MessageBody">
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##any"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
<xs:schema targetNamespace="http://VCI.ESB.NoteServiceOnRamp/Imports"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://VCI.ESB.NoteServiceOnRamp/Imports">
<xs:import namespace="http://VCI.Enterprise.Auditing.GenericNote"/>
<xs:import/>
</xs:schema>
<xs:schema targetNamespace="http://VCI.Enterprise.Auditing.GenericNote"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:b="http://schemas.microsoft.com/BizTalk/2003"
xmlns:ns0="http://VCI.EAI.EventBus.Framework.Schemas.ContextProperties.EnterpriseEventProperties"
xmlns="http://VCI.Enterprise.Auditing.GenericNote">
<xs:annotation>
<xs:appinfo/>
</xs:annotation>
<xs:element name="GenericNote" type="GenericNote">
<xs:annotation>
<xs:appinfo/>
</xs:annotation>
</xs:element>
<xs:complexType name="GenericNote">
<xs:sequence>
<xs:element name="AccountNumber" type="xs:string"/>
<xs:element name="Source" type="xs:string"/>
<xs:element name="NoteType" type="xs:string"/>
<xs:element name="TextField" type="xs:string"/>
<xs:element name="Country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
<xs:schema elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:b="http://schemas.microsoft.com/BizTalk/2003">
<xs:element name="PromiseToPayNoteDetails" nillable="true" type="NotificationDetails"/>
<xs:complexType name="NotificationDetails">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="ApplicationThreadId" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="AccountNumber" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="CountryCode" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="NotificationPaymentDetails" type="NotificationPaymentDetails"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="NotificationPaymentDetails">
<xs:sequence>
<xs:element minOccurs="1" maxOccurs="1" name="PaymentSource" type="PaymentSource"/>
<xs:element minOccurs="0" maxOccurs="1" name="ContactName" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="NoteText" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="PayeeName" type="xs:string"/>
<xs:element minOccurs="1" maxOccurs="1" name="CustomerType" type="AccountPartyType"/>
<xs:element minOccurs="0" maxOccurs="1" name="ConfirmationNumber" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="BankAccountNumber" type="xs:string"/>
<xs:element minOccurs="1" maxOccurs="1" name="WithdrawalDate" type="xs:dateTime"/>
<xs:element minOccurs="1" maxOccurs="1" name="WithdrawalAmount" type="xs:decimal"/>
<xs:element minOccurs="1" maxOccurs="1" name="PaymentType" type="PaymentType"/>
<xs:element minOccurs="1" maxOccurs="1" name="FollowUpDate" type="xs:dateTime"/>
<xs:element minOccurs="1" maxOccurs="1" name="EntryDate" type="xs:dateTime"/>
<xs:element minOccurs="1" maxOccurs="1" name="EmailAddress" type="xs:string"/>
<xs:element minOccurs="1" maxOccurs="1" name="CampaignId" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="PaymentSource">
<xs:restriction base="xs:string">
<xs:enumeration value="None"/>
<xs:enumeration value="CSR"/>
<xs:enumeration value="WEB"/>
<xs:enumeration value="PBP"/>
<xs:enumeration value="IVR"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AccountPartyType">
<xs:restriction base="xs:string">
<xs:enumeration value="PrimaryApplicant"/>
<xs:enumeration value="CoApplicant"/>
<xs:enumeration value="Guarantor"/>
<xs:enumeration value="ThirdParty"/>
<xs:enumeration value="None"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PaymentType">
<xs:restriction base="xs:string">
<xs:enumeration value="OneTimePayment"/>
<xs:enumeration value="PayoffPayment"/>
<xs:enumeration value="RecurringACH"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="NotificationPaymentDetails" nillable="true" type="NotificationPaymentDetails"/>
<xs:element name="PaymentSource" type="PaymentSource"/>
<xs:element name="AccountPartyType" type="AccountPartyType"/>
<xs:element name="PaymentType" type="PaymentType"/>
</xs:schema>
</wsdl:types>
<wsdl:message name="NoteService_SubmitNote_InputMessage">
<wsdl:part name="part" element="q1:GenericNote"
xmlns:q1="http://VCI.Enterprise.Auditing.GenericNote"/>
</wsdl:message>
<wsdl:message name="NoteService_SubmitNote_OutputMessage"/>
<wsdl:message name="NoteService_SubmitPromiseToPayNote_InputMessage">
<wsdl:part name="part" element="PromiseToPayNoteDetails"/>
</wsdl:message>
<wsdl:message name="NoteService_SubmitPromiseToPayNote_OutputMessage"/>
<wsdl:portType name="NoteService">
<wsdl:documentation/>
<wsdl:operation name="SubmitNote">
<wsdl:documentation/>
<wsdl:input message="tns:NoteService_SubmitNote_InputMessage"/>
<wsdl:output message="tns:NoteService_SubmitNote_OutputMessage"/>
</wsdl:operation>
<wsdl:operation name="SubmitPromiseToPayNote">
<wsdl:documentation/>
<wsdl:input message="tns:NoteService_SubmitPromiseToPayNote_InputMessage"/>
<wsdl:output message="tns:NoteService_SubmitPromiseToPayNote_OutputMessage"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="WSHttpBinding_ITwoWayAsyncVoid" type="tns:NoteService">
<wsp:PolicyReference URI="#WSHttpBinding_ITwoWayAsyncVoid_policy"/>
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="SubmitNote">
<wsdl:documentation/>
<soap12:operation soapAction="SubmitNote" style="document"/>
<wsdl:input>
<soap12:body use="literal" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="SubmitPromiseToPayNote">
<wsdl:documentation/>
<soap12:operation soapAction="SubmitPromiseToPayNote" style="document"/>
<wsdl:input>
<soap12:body use="literal" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="BizTalkServiceInstance">
<wsdl:port name="WSHttpBinding_ITwoWayAsyncVoid" binding="tns:WSHttpBinding_ITwoWayAsyncVoid">
<soap12:address location="https://vcipa030c-710dv.usvci001.vci.na.vwg:444/VCI.ESB.NoteServiceOnRamp/NoteService.svc"/>
<wsa10:EndpointReference>
<wsa10:Address>https://vcipa030c-710dv.usvci001.vci.na.vwg:444/VCI.ESB.NoteServiceOnRamp/NoteService.svc</wsa10:Address>
</wsa10:EndpointReference>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

Want to get all Errors List when I validate XML using JAXB

Can you please help me to get the list of all errors when I validate the XML file using JAXB?
Right now I have already implemented the code for the same. I have implemented the code using unmarshalling the XML file.
When I unmarshalling the XML file at that time if any error would be there in the XML file, I got the exception but it came out after giving the first exception but I want the list of all errors of that XML file. This should not come out after getting the first error.
Source xsdFileName = new StreamSource(new File("validate6.xsd"));
Source xmlFileName = new StreamSource(new File("test3.xml"));
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(xsdFileName);
JAXBContext jc = JAXBContext.newInstance(Innovations.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(new MyValidationEventHandler());
Innovations innovation = (Innovations) unmarshaller.unmarshal(xmlFileName);
System.out.println("Total Size :: " + innovation.getInnovationList().size());
System.out.println(xmlFileName.getSystemId() + " is valid");
} catch (JAXBException e) {
e.printStackTrace();
System.out.println(xmlFileName.getSystemId() + " is NOT valid");
} catch (SAXParseException e) {
e.printStackTrace();
System.out.println(xmlFileName.getSystemId() + " is NOT valid");
} catch (SAXException e) {
e.printStackTrace();
System.out.println(xmlFileName.getSystemId() + " is NOT valid");
}
XSD File:
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="innovations">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="organization" />
<xs:element name="innovation" maxOccurs="unbounded"
minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="title" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="brief_description" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="categories" minOccurs="1">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="category" maxOccurs="unbounded"
minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="tags" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="tag" maxOccurs="unbounded"
minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="full_description" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="patent_number" maxOccurs="unbounded" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="patent_status" maxOccurs="unbounded" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="case_manager" minOccurs="1">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute type="xs:string" name="first_name"
use="optional" />
<xs:attribute type="xs:string" name="last_name"
use="optional" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="status" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
<xs:attribute type="xs:short" name="file_number" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
Validation Event Handler Class
public class MyValidationEventHandler implements ValidationEventHandler {
public boolean handleEvent(ValidationEvent event) {
System.out.println("\nEVENT");
switch (event.getSeverity()) {
case 0:
System.out.println("SEVERITY: WARNING");
break;
case 1:
System.out.println("SEVERITY: ERROR");
break;
case 2:
System.out.println("SEVERITY: FATAL_ERROR");
break;
}
System.out.println("MESSAGE: " + event.getMessage());
System.out.println("LINKED EXCEPTION: " + event.getLinkedException());
System.out.println("LOCATOR");
System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println(" OFFSET: " + event.getLocator().getOffset());
System.out.println(" OBJECT: " + event.getLocator().getObject());
System.out.println(" NODE: " + event.getLocator().getNode());
System.out.println(" URL: " + event.getLocator().getURL());
return true;
}
}
Output:
EVENT
SEVERITY: FATAL_ERROR
MESSAGE: cvc-complex-type.2.4.a: Invalid content was found starting with element 'case_manager1'. One of '{patent_status, case_manager}' is expected.
LINKED EXCEPTION: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 24; columnNumber: 55; cvc-complex-type.2.4.a: Invalid content was found starting with element 'case_manager1'. One of '{patent_status, case_manager}' is expected.
LOCATOR
LINE NUMBER: 24
COLUMN NUMBER: 55
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml
EVENT
SEVERITY: ERROR
MESSAGE: unexpected element (uri:"", local:"case_manager1"). Expected elements are <{}tags>,<{}title>,<{}patent_number>,<{}brief_description>,<{}status>,<{}full_description>,<{}categories>,<{}case_manager>,<{}patent_status>
LINKED EXCEPTION: null
LOCATOR
LINE NUMBER: 24
COLUMN NUMBER: 55
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml
EVENT
SEVERITY: FATAL_ERROR
MESSAGE: The element type "case_manager1" must be terminated by the matching end-tag "".
LINKED EXCEPTION: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".
LOCATOR
LINE NUMBER: 25
COLUMN NUMBER: 5
OFFSET: -1
OBJECT: null
NODE: null
URL: file:/D:/AHWeb2.0.3/test3.xml
file:/D:/AHWeb2.0.3/test3.xml is NOT valid
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:514)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:215)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:184)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
at com.test.innovation.validation.InnovationUnmarshalDemo.main(InnovationUnmarshalDemo.java:34)
Caused by: org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:211)
... 4 more
Thanks.
I guess a custom validator will help you:
public class MyValidationEventHandler implements ValidationEventHandler{
public boolean handleEvent(ValidationEvent ve) {
if (ve.getSeverity()==ve.FATAL_ERROR ||
ve .getSeverity()==ve.ERROR){
ValidationEventLocator locator = ve.getLocator();
//print message from valdation event
System.out.println("Message is " + ve.getMessage());
//output line and column number
System.out.println("Column is " +
locator.getColumnNumber() +
" at line number " + locator.getLineNumber());
}
return true;
}
}
and then
setEventHandler(new MyValidationEventHandler());
Ok, so the problem lies here:
/test3.xml is NOT valid javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException; systemId: file:/D:/AHWeb2.0.3/test3.xml; lineNumber: 25; columnNumber: 5; The element type "case_manager1" must be terminated by the matching end-tag "".] at javax.xml.bind.helpers.AbstractUnmarshallerI mpl.createUnmarshalException(Unknown Source) at...
Line 25 of your XML is not correct - it is missing an end tag.
This mechanism for schema validation cannot continue passed a severe error as the XML is not syntactically correct.

SAXParserException while trying to read the xsd

My project has a JAXWS class where an XSD is read and finally validated in another method.
Here is the java code where they read the XSD
private static final ThreadLocal <DocumentBuilder> parser =
new ThreadLocal <DocumentBuilder> () {
#Override protected DocumentBuilder initialValue() {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// loading Schema file
//System.out.println("Hi .. am in parser");
DocumentBuilder parserBuilder = null;
if(finalXsd !=null){
logger.info("finalXsd FILE"+finalXsd);
Source schemaFile = new StreamSource(new File(finalXsd));
try{
logger.info ("place-0") ;
Schema schema = factory.newSchema(schemaFile);
logger.info ("place-1") ;
docBuilderFactory.setValidating(false); // true is used for DTD based validation, for schema validation set to false
logger.info ("place-2") ;
docBuilderFactory.setSchema(schema);
logger.info ("place-3") ;
parserBuilder = docBuilderFactory.newDocumentBuilder();
logger.info ("place-4") ;
parserBuilder.setErrorHandler( new JythonResponseErrorHandler() );
logger.info ("place-5") ;
}catch(SAXException s)
{
logger.error("SAXException in ThreadLocal.");
s.printStackTrace() ;
return null;
} catch (ParserConfigurationException e) {
e.printStackTrace();
logger.error("ParserConfigurationException in ThreadLocal.");
return null;
}
}
return parserBuilder;
}
};
XSD FILE (which the above code trying to read) :
<?xml version="1.0" encoding="UTF-8"?>
<!--W3C Schema generated by XMLSpy v2010 rel. 2 (http://www.altova.com) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="TAG">
<xs:complexType>
<xs:attribute name="name" use="required" type="xs:string" />
<xs:attribute name="value" use="optional" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="STRING">
<xs:complexType>
<xs:sequence>
<xs:element ref="EN" />
<xs:element ref="ES" />
</xs:sequence>
<xs:attribute name="name" use="required" type="xs:string">
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="FRACTION">
<xs:complexType>
<xs:sequence>
<xs:element ref="N" />
<xs:element ref="D" />
</xs:sequence>
<xs:attribute name="name" use="required" >
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="RESULTLIST">
<xs:complexType>
<xs:sequence>
<xs:element ref="RESPONSE" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="RESPONSE">
<xs:complexType mixed="true" >
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="PLURAL">
<xs:complexType>
<xs:sequence>
<xs:element ref="STRING" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="NAME">
<xs:complexType>
<xs:sequence>
<xs:element ref="STRING" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="INTEGER">
</xs:element>
<xs:element name="ID" type="xs:int">
</xs:element>
<xs:element name="GENDER">
<xs:complexType>
<xs:sequence>
<xs:element ref="STRING" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="BOOL">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:boolean">
<xs:attribute name="name" use="required" type="xs:string">
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="FILE_ID" type="xs:int">
</xs:element>
<xs:element name="ES" type="xs:string" />
<xs:element name="EN" type="xs:string" />
<xs:element name="N" type="xs:int" />
<xs:element name="D" type="xs:int" />
<xs:element name="DICTIONARY">
<xs:complexType mixed="true">
<xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
<xs:attribute name="name" use="required" type="xs:string">
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="ASSET">
<xs:complexType>
<xs:sequence>
<xs:element ref="NAME" />
<xs:element ref="PLURAL" />
<xs:element ref="ALTTEXT" />
<xs:element ref="GENDER" />
<xs:element ref="ID" />
<xs:element ref="FILE_ID" />
<xs:element ref="DICTIONARY" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="name" use="required" >
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="ARRAY">
<xs:complexType>
<xs:choice>
<xs:element ref="ARRAY" minOccurs="0" maxOccurs="unbounded" />
<xs:element ref="STRING" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="ASSET" maxOccurs="unbounded"/>
<xs:element ref="INTEGER" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="FRACTION" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="DICTIONARY" minOccurs="0" maxOccurs="unbounded"/>
</xs:choice>
<xs:attribute name="name" use="required" type="xs:string">
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="ALTTEXT">
<xs:complexType>
<xs:sequence>
<xs:element ref="STRING" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
while sending a response from SOAP-UI, the above code gets executed and throws below exception
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'file:/D:/softwares/jboss-5.1.0.GA/server/default/deploy/poctest.war/WEB-INF/classes/final.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>.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaError(Unknown Source)
at org.apache.xerces.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source)
at org.apache.xerces.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar(Unknown Source)
at org.apache.xerces.jaxp.validation.XMLSchemaFactory.newSchema(Unknown Source)
at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:594)
at com.hmco.ssms.services.poc.SoarPocJaxWS$1.initialValue(SoarPocJaxWS.java:59)
at com.hmco.ssms.services.poc.SoarPocJaxWS$1.initialValue(SoarPocJaxWS.java:46)
at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:141)
at java.lang.ThreadLocal.get(ThreadLocal.java:131)
at com.hmco.ssms.services.poc.SoarPocJaxWS.getParametersMultiple(SoarPocJaxWS.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.wsf.container.jboss50.invocation.InvocationHandlerJSE.invoke(InvocationHandlerJSE.java:108)
at org.jboss.ws.core.server.ServiceEndpointInvoker.invoke(ServiceEndpointInvoker.java:222)
at org.jboss.wsf.stack.jbws.RequestHandlerImpl.processRequest(RequestHandlerImpl.java:474)
at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleRequest(RequestHandlerImpl.java:295)
at org.jboss.wsf.stack.jbws.RequestHandlerImpl.doPost(RequestHandlerImpl.java:205)
at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleHttpRequest(RequestHandlerImpl.java:131)
at org.jboss.wsf.common.servlet.AbstractEndpointServlet.service(AbstractEndpointServlet.java:85)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
I even tried changing XS to XSD in the xsd file. but stil i get this exception.
Please help me on this
Thanks
Arun
Issue is fixed,
This is because, in jboss-5 the files inside the WAR file cannot be read using getResource() and hence there were no proper file-binding SchemaFactory
I changed the path of the file and now it is working cool !!

xml schema, precision of decimal value

This is my xml (not whole):
<xsd:complexType name="xx">
<xsd:complexContent>
<xsd:extension base="tns:xx">
<xsd:sequence>
<xsd:element name="rekVrednostDdv" nillable="true" type="decimal"/>
<xsd:element name="xx" nillable="true" type="dateTime"/>
<xsd:element name="xx" nillable="true" type="decimal"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="dateTime"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="decimal"/>
<xsd:element name="xx" nillable="true" type="decimal"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="decimal"/>
<xsd:element name="xx" nillable="true" type="tns:xx"/>
<xsd:element name="xx" nillable="true" type="dateTime"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="string"/>
<xsd:element name="xx" nillable="true" type="string"/>
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
For example rekVrednostDdv must have precision 2. How can i tell this type to have precision 2.
i try like this:
<xsd:element name="rekVrednostDdv" nillable="true">
<xsd:simpleType>
<xsd:restriction base="decimal">
<xsd:precision value="6"/>
<xsd:scale value="2"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
but now i get when using http://www.brainbell.com/tutorials/XML/Working_With_Simple_Types.htm
Invalid XML schema: 'Element <xsd:precision> is not allowed under element <xsd:restriction>.'
Create a new simple type that restricts xs:decimal and use <xs:fractionDigits/> to define the precision. Then refer to this type in your element definition.
<xs:simpleType name="decimalTwoPrec">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="2" />
</xs:restriction>
</xs:simpleType>
<xs:element name="rekVrednostDdv" nillable="true" type="decimalTwoPrec"/>
For more info, see the spec http://www.w3.org/TR/xmlschema-2/#rf-fractionDigits

Polymorphism in XSD schema and JAXB classes

I have an xml like this:
<todo>
<doLaundry cost="1"/>
<washCar cost="10"/>
<tidyBedroom cost="0" experiencePoints="5000"/>
</todo>
And the XSD schema for it is:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="todo">
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="doLaundry" type="doLaundry" />
<xs:element name="washCar" type="washCar" />
<xs:element name="tidyBedroom" type="tidyBedroom" />
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="doLaundry">
<xs:attribute name="cost" type="xs:int" />
</xs:complexType>
<xs:complexType name="washCar">
<xs:attribute name="cost" type="xs:int" />
</xs:complexType>
<xs:complexType name="tidyBedroom">
<xs:attribute name="cost" type="xs:int" />
<xs:attribute name="experiencePoints" type="xs:int" />
</xs:complexType>
</xs:schema>
And when I process this schema through JAXB I get a class with a method like this:
public class Todo {
public List<Object> getDoLaundryOrWashCarOrTidyBedroom() {
...
}
}
Ideally, what I would like is a way to define a generic base type that all the other XSD types extend. The Jaxb classes generated from the XSD schema should have a method to return a list of generic tasks. This would make it very easy to add new tasks to the todo list:
public class Todo {
public List<Task> getTasks() {
...
}
}
public abstract class Task {
public int getCost() {
...
}
}
public class TidyBedroom extends Task {
public int getExperiencePoints() {
...
}
}
What should the XSD schema look like in order to generate the above Java classes?
I found the answer with the help of Blaise Doughan's article here: http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-xsitype.html
This schema:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="todo">
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="doLaundry" type="doLaundry" />
<xs:element name="washCar" type="washCar" />
<xs:element name="tidyBedroom" type="tidyBedroom" />
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType abstract="true" name="Task">
<xs:attribute name="cost" type="xs:int" use="required" />
</xs:complexType>
<xs:complexType name="doLaundry">
<xs:complexContent>
<xs:extension base="Task">
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="washCar">
<xs:complexContent>
<xs:extension base="Task">
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="tidyBedroom">
<xs:complexContent>
<xs:extension base="Task">
<xs:attribute name="experiencePoints" type="xs:int" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
combined with a binding file:
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings>
<jxb:bindings schemaLocation="todo.xsd" node="/xs:schema/xs:complexType[#name='todo']/xs:sequence/xs:choice">
<jxb:property name="Tasks"/>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
Will give abstract and inherited classes as I described in the question. The binding file will change Jaxb's default method name from getDoLaundryOrWashCarOrTidyBedroom() to getTasks().
xsd:choice corresponds to the #XmlElements annotation. You could apply this annotation directly to your desired object model.
For more information see:
http://bdoughan.blogspot.com/2010/10/jaxb-and-xsd-choice-xmlelements.html
Use xs:extension in your schema and your JAXB classes will be inherited (extended) as you define in your schema.
Maybe I'm not 'getting' the question, but what is wrong with..
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="todo">
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="doLaundry" type="task" />
<xs:element name="washCar" type="task" />
<xs:element name="tidyBedroom" type="task" />
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name="task">
<xs:attribute name="cost" type="xs:int" />
<xs:attribute name="experiencePoints" type="xs:int" />
</xs:complexType>
</xs:schema>

Resources