JAXB(2): can one suppress the unwanted list-wrapper element - jaxb

For elements with multiplicity > 1 (i.e.. where maxOccurs>1 or maxOccurs=unbound), e.g.:
<element name="Name" type="tns:Type" minOccurs="0" maxOccurs="unbound"/>
JAXB generates the following code:
#XmlElement(name = "Name")
protected List<type> name;
Strictly speaking the above schema describes an XML snippet that looks like so:
<Name attr1="a" attr2="x">
<Name attr1="b" attr2="y">
<Name attr1="c" attr2="z">
i.e. a sequence of "Name" elements (and only that!).
When marshalling a Java object to XML the JAXB runtime creates XML, which contains an additional wrapper element around the list, like so:
<Name>
<Name attr1="a" attr2="x">
<Name attr1="b" attr2="y">
<Name attr1="c" attr2="z">
<Name>
By default the wrapping element has the same name as the individual items. Note, that there is no Java class representing that element!
One can overrule the naming to something that makes more sense by manually (!) adding a java-annotation "#XmlElementWrapper" annotation, like so:
#XmlElementWrapper(name = "NameList")
#XmlElement(name = "Name")
protected List<Type> name;
which then yields the following XML:
<NameList>
<Name attr1="a" attr2="x">
<Name attr1="b" attr2="y">
<Name attr1="c" attr2="z">
<NameList>
I agree that such a wrapper element is syntactically nice and makes the XML more readable, BUT there is a severe problem with this: the generated Java code (with or without renaming the wrapper element) generates and expects an XML dialect which - strictly speaking - does not match the original schema anymore! There is no mentioning or any implicit notion of any such wrapper element in the original schema!
The issue only surfaces, if one uses the original schema in different tools (e.g. to create web forms or a different schema-based code generator) and if their result then adheres and/or expects the original XML (i.e. the bare sequence without any wrapper element), while the JAXB-generated code creates and insists on the presence of the wrapper element. Then the two cannot understand each other!
My question thus: how can one instruct JAXB to NOT add/expect said wrapper element while marshalling/unmarshalling XML?
I have searched the web now for quite a while for solutions or work-arounds to this but found nothing! I can't imagine that nobody else before ever stumbled over this and that there seems no other solution to this other problem than to hand-tweak the XML marshalling/unmarshalling code. Any ideas or suggestions to solve this issue?

Related

XJC xsd:any parsing

I have an element in XSD schema:
<xsd:any processContents="skip"/>
Is it possible to switch processContents to strict through XJB binding? Without modifying schema file. May be set it as global property. I want to get:
#XmlAnyElement(lax = true)
protected Object any;
instead of:
#XmlAnyElement
protected Element any;
You could totally change the annotation and the attribut's type. But beware if you generate your code from the XSD your modifications would be crushed.
Could you explain a little bit more your work context, needs and goals. Why can't you touch the XSD, do you generate classes from the XSD by JaxB? Do you use the XSD for validation purposes?

WSImport generates conflicting XMLTypes for multiple Dynamics CRM 4.0 WSDL's

I'm currently working with the Dynamics CRM 4.0 webservice. First thing I did, was generating the right classes with wsimport for Java/JAX-WS based on the WSDL of the webservice. While generating the classes I got some errors:
[ERROR] A class/interface with the same name
"com.microsoft.schemas.crm._2007.webservices.RetrieveResponse" is already in use. Use a class customization to resolve this conflict.
line 979 of file://src/main/webapp/WEB-INF/classes/META-INF/wsdl/CrmServiceWsdl.wsdl
[ERROR] (Relevant to above error) another "RetrieveResponse" is generated from here.
line 12274 of file://src/main/webapp/WEB-INF/classes/META-INF/wsdl/CrmServiceWsdl.wsdl
Line 979 tells us:
<s:element name="RetrieveResponse">
<s:complexType>
<s:sequence>
<s:element name="RetrieveResult" type="s3:BusinessEntity" />
</s:sequence>
</s:complexType>
</s:element>
And line 12274 gives us:
<s:complexType name="RetrieveResponse">
<s:complexContent mixed="false">
<s:extension base="tns:Response">
<s:sequence>
<s:element ref="s3:BusinessEntity" />
</s:sequence>
</s:extension>
</s:complexContent>
</s:complexType>
Both parts are in the same namespace. Both will be generated as RetrieveResponse.class and so they are colliding. I've found a solution for this problem which is the JAX-B binding xml file:
<bindings node="//xsd:complexType[#name='RetrieveResponse']">
<jaxb:class name="RetrieveResponseType"/>
</bindings>
This works (not sure if this is the correct approach..?)..
So after this, I've managed to create some successful calls to the webservice, which is great!
Now comes the problem: some business entities in dynamics crm uses the class Picklist. This type of entity can be queried with the Metadata service: http://msdn.microsoft.com/en-us/library/bb890248.aspx
So the next thing I did was, again, generating the classes for the metadata service, based on it's WSDL. The result of the generated classes are not as we except. For example, it generates a class 'com.microsoft.schemas.crm._2007.webservices.ExecuteResponse'. But this class also exists in the exact same package of the CrmService generated classes. Differences between the 2 are:
Metadataservice ExecuteReponse:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"response"
})
#XmlRootElement(name = "ExecuteResponse")
public class ExecuteResponse {
#XmlElement(name = "Response")
protected MetadataServiceResponse response;
etc...
CrmService ExecuteReponse:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"response"
})
#XmlRootElement(name = "ExecuteResponse")
public class ExecuteResponse {
#XmlElement(name = "Response", required = true)
protected ResponseType response;
etc...
Now this class is just one example (another example is CrmAuthenticationToken), which is a almost exact duplicate of another class. To be able to use the same classes, I've added a package-suffix to the CrmService classes (displayed as prefix.).
So now when I try to call the CrmService, I get the following exception:
Two classes have the same XML type name "{http://schemas.microsoft.com/crm/2007/CoreTypes}CrmAuthenticationToken". Use #XmlType.name and #XmlType.namespace to assign different names to them.
this problem is related to the following location:
at com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken
at public com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken *prefix*.com.microsoft.schemas.crm._2007.coretypes.ObjectFactory.createCrmAuthenticationToken()
at *prefix*.com.microsoft.schemas.crm._2007.coretypes.ObjectFactory
this problem is related to the following location:
at *prefix*.com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken
at public javax.xml.bind.JAXBElement *prefix*.com.microsoft.schemas.crm._2007.webservices.ObjectFactory.createCrmAuthenticationToken(*prefix*.com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken)
at *prefix*.com.microsoft.schemas.crm._2007.webservices.ObjectFactory
I personally think it's weird they put different classes with the same name in the same package structure. This means you can never use the 2 webservices at the same time..
Is this a Microsoft, a WSimport bug or just a stupid mistake at my end? Hope somebody can help me with this problem!
Thanks for your time!
This is Microsoft inconsistency combined with wsimport being somewhat hard to use.
The PickList and the CRMAuthenticationToken sound like custom datatypes, you'd expect for these to get reused from service to service.
You'd also expect certain CRM-specific entities (say, Customer or Business or Address) to get reused from service to service.
It is bad manners on the Microsoft side of things that they define these differently for different services. This makes it hard to take the answer of one service and send it on to another service.
Had the services shared one or more common schemas, you could've compiled those first, using xjc. Then you could've provided a so-called episode file to wsimport to tell it to use those classes instead of generating new ones. See the metro guide. This is quite a puzzle, I can tell you from experience, I ran into bug JAXB-829, xjc forgets to generate if-exists attributes in the episode file.
What I'd do, I'd compile each wsdl to its own package and treat the generated classes as simple unintelligent Data Transfer Objects.
If I wanted to send an object I'd just retrieved from one service on to a second service, I'd convert between the both.
If this results in terribly unwieldy code, or if you wish to add logic to certain entities, I'd suggest you write your own proper model classes for the Entities you wish to share and write converters to and from the DTO objects in the web services packages you wish to use them with.

Using nillable elements in BizTalk expressions

I have nillable decimal element defined in xsd schema like this:
<xs:element name="myDecimalValue" nillable="true" type="xs:decimal" />
This is distinguished field and I want to check if it is nill in expression shape. I could use xpath() function like this:
xpath("string(//*[local-name()='myDecimalValue']/#*[local-name()='nil'])") == "true"
But it looks a little bit complicated for simple null-checking. So I'm wondering if I'm missing something and there is better way to do it?
you can try to use a decide shape instead of the xpath
your decide shape will lok like this
just ask if myDecimalValue is null
msgName.myDecimalValue != null here
than you can continue your logic
if you using a distinguished field use it its more readable for other dev
EDIT:
can you try
varString = System.Convert.ToString(msgName.myDecimalValue);
and then ask if varString is null or not
i tried it and it compile well
hopes it help
:)
I have a suspicion that this can't be achieved.
Specifically, from http://support.microsoft.com/kb/942250
Properties that have a null value are not permitted in the message
context. Therefore, if a null value is written into the message
context, this value will be deleted.
(this is in the document section relating to Promoted and Distinguished properties, so I am assuming it is applicable to both).
So it looks like your xpath solution might be the required solution, as the distinguished property won't be in the message context anyway.

How to compare 2 xsd schema files for equivalent functionality

I would like to compare 2 XSD schemas A and B to determine that all instance documents valid to schema A would also be valid to schema B. I hope to use this to prove that even though schema A and B are "different" they are effectively the same. Examples of differences this would not trigger would be Schema A uses types and Schema B declares all of it's elements inline.
I have found lots of people talking about "smart" diff type tools but these would claim the two files are different because they have different text but the resulting structure is the same. I found some references to XSOM but I'm not sure if that will help or not.
Any thoughts on how to proceed?
Membrane SOA Model - Java API for WSDL and XML Schema
package sample.schema;
import java.util.List;
import com.predic8.schema.Schema;
import com.predic8.schema.SchemaParser;
import com.predic8.schema.diff.SchemaDiffGenerator;
import com.predic8.soamodel.Difference;
public class CompareSchema {
public static void main(String[] args) {
compare();
}
private static void compare(){
SchemaParser parser = new SchemaParser();
Schema schema1 = parser.parse("resources/diff/1/common.xsd");
Schema schema2 = parser.parse("resources/diff/2/common.xsd");
SchemaDiffGenerator diffGen = new SchemaDiffGenerator(schema1, schema2);
List<Difference> lst = diffGen.compare();
for (Difference diff : lst) {
dumpDiff(diff, "");
}
}
private static void dumpDiff(Difference diff, String level) {
System.out.println(level + diff.getDescription());
for (Difference localDiff : diff.getDiffs()){
dumpDiff(localDiff, level + " ");
}
}
}
After executing you get the output shown in listing 2. It is a List of
differences between the two Schema documents.
ComplexType PersonType has changed: Sequence has changed:
Element id has changed:
The type of element id has changed from xsd:string to tns:IdentifierType.
http://www.service-repository.com/ offers an online XML Schema Version Comparator tool that displays a report of the differences between two XSD that appears to be produced from the Membrane SOA Model.
My approach to this was to canonicalize the representation of the XML Schema.
Unfortunately, I can also tell you that, unlike canonicalization of XML documents (used, as an example, to calculate a digital signature), it is not that simple or even standardized.
So basically, you have to transform both XML Schemas to a "canonical form" - whatever the tool you build or use thinks that form is, and then do the compare.
My approach was to create an XML Schema set (could be more than one file if you have more namespaces) for each root element I needed, since I found it easier to compare XSDs authored using the Russian Doll style, starting from the PSVI model.
I then used options such as auto matching substitution group members coupled with replacement of substitution groups with a choice; removal of "superfluous" XML Schema sequences, collapsing of single option choices or moving minOccurs/maxOccurs around for single item compositors, etc.
Depending on what your XSD-aware comparison tool's features are, or you settle to build, you might also have to rearrange particles under compositors such as xsd:choice or xsd:all; etc.
Anyway, what I learned after all of it was that it is extremely hard to build a tool that would work nice for all "cool" XSD features out there... One test case I remember fondly was to deal with various xsd:any content.
I do wonder though if things have changed since...

JAXB Unable To Handle Attribute with Colon (:) in name?

I am attempting to use JAXB to unmarshall an XML files whose schema is defined by a DTD (ugh!).
The external provider of the DTD has specified one of the element attributes as xml:lang:
<!ATTLIST langSet
id ID #IMPLIED
xml:lang CDATA #REQUIRED
>
This comes into the xjc-generated class (standard generation; no *.xjb magic) as:
#XmlAttribute(name = "xml:lang", required = true)
#XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlLang;
However, when unmarshalling valid XML files with JAXB, the xmlLang attribute is always null.
When I edited the XML file, replacing xml:lang with lang and changed the #XmlAttribute to match, unmarshalling was successful (i.e. attributes were non-null).
I did find this http://old.nabble.com/unmarshalling-ignores-element-attribute-%27xml%27-td22558466.html. But, the resolution there was to convert to XML Schema, etc. My strong preference is to go straight from an un-altered DTD (since it is externally provided and defined by an ISO standard).
Is this a JAXB bug? Am I missing something about "namespaces" in attribute names?
FWIW, java -version = "build 1.6.0_20-b02" and xjc -version = "xjc version "JAXB 2.1.10 in JDK 6""
Solved the issue by changing replacing xml: with a namespace declaration in the JAXB-generated class:
#XmlAttribute(name = "lang", namespace="http://www.w3.org/XML/1998/namespace", required = true)
Which makes sense, in a way.
Without this kind of guidance, how would JAXB know how to interpret the otherwise-undefined namespace xml:? Unless, of course, it implemented some special-case internal handling to xml: as done in http://java.sun.com/javase/6/docs/api/javax/xml/stream/XMLStreamReader.html#getNamespaceURI%28java.lang.String%29 (see the first NOTE:)
Whether it's a bug in xjc's generation of the annotated objects or a bug in the unmarhaller, or simply requires a mapping somewhere in the xjc process is still an open question in my mind.
For now, it's working and all it requires is a little xjc magic, so I'm reasonably happy.
Disclaimer: Although 8 years late, I am adding this answer for lost souls such as myself trying to understand auto generation of java files from a DTD.
You can set project wide namespaces for the unmarshaller to work with directly in the project-info.java file via the #XmlSchema option.
This file should be automatically generated by xjc when generating classes from a schema, however it appears xjc does not automatically generate the package-info.java file when generating from a DTD!
However, you can manually make this file, and add it to the same package as the files generated by xjc.
The file would look like the following:
package-info.java :
#XmlSchema(
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns = {
#XmlNs(prefix="xlink", namespaceURI="http://www.w3c.org/1999/xlink"),
#XmlNs(prefix="namespace2", namespaceURI="http://www.w3c.org/1999/namespace2")
})
package your.generated.package.hierarchy;
import javax.xml.bind.annotation.*;
You can add as many namespaces as required, simply add a new line in the form:
#XmlNs(prefix="namespace", namespaceURI="http://www.uri.to.namespace.com")
The benefit of doing it this way, rather than compared to editing the generated #XmlAttribute is that you do not need to change each generated XmlAttribute, and you do not need to manually remove the namespaces from the XmlAttribute name variable.

Resources