JAXB fragment with different namespaces - java

I have to marshall a fragment of my root xml object :
Header header = ebicsNoPubKeyDigestsRequest.getHeader();
JAXBElement<org.ebics.h003.EbicsNoPubKeyDigestsRequest.Header> jaxbElement =
new JAXBElement<EbicsNoPubKeyDigestsRequest.Header>(
new QName("header"), EbicsNoPubKeyDigestsRequest.Header.class, header);
byte[] headerXml = JAXBHelper.marshall(jaxbElement, true);
but when I marshall ebicsNoPubKeyDigestsRequest the namespaces are not the same (in header fragment I have : xmlns:ns4="http://www.ebics.org/H003" but in ebicsNoPubKeyDigestsRequest I have xmlns="http://www.ebics.org/H003")
If I marshall the header object directly, without using JAXBElement, I have an No #XmlRootElement error
How I can have the same namespaces?
NB : I already use a NamespacePrefixMapper class :
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
#Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
if (namespaceUri.equals("http://www.ebics.org/H003")) {
return "";
} else if (namespaceUri.equals("http://www.w3.org/2000/09/xmldsig#")) {
return "ds";
} else if (namespaceUri.equals("http://www.ebics.org/S001")) {
return "ns1";
} else if (namespaceUri.equals("http://www.w3.org/2001/XMLSchema-instance")) {
return "ns2";
}
return "";
}
});
EDIT : here the different package-info.java :
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.ebics.org/H003", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.ebics.h003;
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.ebics.org/S001", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.ebics.s001;
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/2000/09/xmldsig#", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.w3._2000._09.xmldsig_;

Without seeing your actual XML schema, files and JAXB generated classes (and their annotations) I can only advise you to try an adapt the following example to your scenario.
Given that you have a JAXB generated class like the following:
#XmlRootElement(namespace = "http://test.com")
#XmlType(namespace = "http://test.com")
public static final class Test {
public String data;
public Test() {}
}
which is in the package test and there is a package-info.java file in it like this:
#XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = #XmlNs(prefix = "", namespaceURI = "http://test.com"))
package test;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
the following code:
Test test = new Test();
test.data = "Hello, World!";
JAXBContext context = JAXBContext.newInstance(Test.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(test, System.out);
will print this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test xmlns="http://test.com">
<data>Hello, World!</data>
</test>
You can probably probably omit a the NamespacePrefixMapper implementation entirely.
Play with omitting particular namespace elements from any of the annotations and see how the output changes.
Blaise Doughan (a Java XML binding expert, probably lurking around somewhere near) has posted some info regarding this issue on his blog, see his post for some more insight.
Based on the input provided by Baptiste in chat I propose the following solution (I think this is the most painless).
Compile your schema files with XJC normally ($ xjc .). This will generate package-java.info files for each of the generated packages. I assume this schema isn't updated everyday, so you're safe to make modifications on the package-info.java files (even though there will be some line comments in those files telling you not to do it—do it anyway). If the schema gets updated and you have to re-compile it run XJC with the -npa switch, which tells it not to generate those package-info.java files automatically, so (ideally) you can't overwrite your hand-crafted files (if you use version control you can/should include these (handmade) files in the repository).
Based on the provided schema files four packages are generated, so I'll include my version of the modified package-info.java files.
#XmlSchema(namespace = "http://www.ebics.org/H000",
xmlns = #XmlNs(prefix = "ns1",
namespaceURI = "http://www.ebics.org/H000"))
package org.ebics.h000;
#XmlSchema(namespace = "http://www.ebics.org/H003",
xmlns = #XmlNs(prefix = "",
namespaceURI = "http://www.ebics.org/H003"))
package org.ebics.h003;
#XmlSchema(namespace = "http://www.ebics.org/S001",
xmlns = #XmlNs(prefix = "ns3",
namespaceURI = "http://www.ebics.org/S001"))
package org.ebics.s001;
#XmlSchema(namespace = "http://www.w3.org/2000/09/xmldsig#",
xmlns = #XmlNs(prefix = "ns2",
namespaceURI = "http://www.w3.org/2000/09/xmldsig#"))
package org.w3._2000._09.xmldsig;
After this you create your JAXBContext like this:
JAXBContext context =
JAXBContext.newInstance("org.ebics.h003:org.ebics.s001:org.w3._2000._09.xmldsig");
(I've noticed that you don't use actually use the h000 package so I've omitted it from the package name list. If it is included, then the marshalled XML's root tag will probably contain its namespace and prefix mapping, even tough it isn't used.)
After this, you unmarshall your input XML and do whatever you want to with the object in memory.
Unmarshaller unmarshaller = context.createUnmarshaller();
EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest =
(EbicsNoPubKeyDigestsRequest) unmarshaller.unmarshal(stream);
Now, if you want to marshall only the header tag which is nested inside the ebicsNoPubKeyDigestsRequest you have to wrap it inside a JAXBElement<...> because the header's type EbicsNoPubKeyDigestsRequest.Header isn't annotated with the #XmlRootElement annotation. You have two (in this case one) way to create this element.
Create an ObjectFactory instance for the corresponding package and use its JAXBElement<T> createT(T t) function. Which wraps its input into a JAXBElement<...>. Unfortunately however, for the header field's type (given your schema files) XJC generates no such method, so you have to do it by hand.
Basically you've almost done it right, but when creating the JAXBElement<...> instead of passing it new QName("header") you have to create a fully-qualifed name, which implies that the namespace is specified too. Passing only the name of the XML tag isn't sufficient, because JAXB won't know this way that this particular header tag is part of the "http://www.ebics.org/H003" namespace. So do it like this:
QName qualifiedName = new QName("http://www.ebics.org/H003", "header");
JAXBElement<EbicsNoPubKeyDigestsRequest.Header> header =
new JAXBElement<EbicsNoPubKeyDigestsRequest.Header>(
qualifiedName, EbicsNoPubKeyDigestsRequest.Header.class, header);
I didn't test if changing only the QName instantiation solves your problem, but maybe it will. However I think it won't and you have to manually manage your prefixes to get a nice and consistent result.

Related

Create XML Node with attribute xsi:type in JDOM2

I am trying to create the below XML document .
<?xml version="1.0" encoding="UTF-8"?>
<BCPFORMAT>
<RECORD>
<FIELD ID="1" xsi:type="CharFixed" MAX_LENGTH="4" />
</RECORD>
</BCPFORMAT>
I'm using the Java Code as below -
package com.tutorialspoint.xml;
import java.awt.List;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class createXmlLayout {
public static void main(String[] args) {
Document doc = new Document();
Element root = new Element("BCPFORMAT");
//RECORD Element
Element child = new Element("RECORD");
//FIELD Element
Element name = new Element("FIELD")
.setAttribute("ID", "1")
.setAttribute("xsi:type", "CharFixed")
.setAttribute("MAX_LENGTH", "4");
child.addContent(name);
root.addContent(child);
doc.addContent(root);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
try {
outputter.output(doc, System.out);
outputter.output(doc, new FileWriter("c:\\VTG_MAPN.xml"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
But I'm getting the below error:
The name "xsi:type" is not legal for JDOM/XML attributes: XML name 'xsi:type' cannot contain the character ":".
I know I might need to use Namespace but how I'm not able to figure out.
JDOM doesn't allow you to create paths containing colons (:) that way, due to XML 1.0 specifications on : being reserved to namespaces. Check JDOM's FAQ here.
To set or create an attribute that uses a namespace you must use a function/constructor that accepts a namespace as a parameter.
In this case, you could use the following:
e.setAttribute("type", "CharFixed", Namespace.getNamespace("xsi", "xsi_uri"));
UPDATE:
We can add a namespace declaration inside one of the parents of the child (FIELD), and set the child to use this namespace for a given attribute.
Namespace namespace = Namespace.getNamespace("xsi", "xsi_uri");
root.addNamespaceDeclaration(namespace);
// ...
Element name = new Element("FIELD")
.setAttribute("ID", "1")
.setAttribute("type", "CharFixed", root.getNamespacesInScope().get(2))
.setAttribute("MAX_LENGTH", "4");
// ...
The output will be the following:
<?xml version="1.0" encoding="UTF-8"?>
<BCPFORMAT xmlns:xsi="xsi_uri">
<RECORD>
<FIELD ID="1" xsi:type="CharFixed" MAX_LENGTH="4" />
</RECORD>
</BCPFORMAT>
This feature is part of the NamespaceAware Interface
Why get(2):
if we get the inherited namespace list for the root element it will return 3 namespaces, described by the following text:
[Namespace: prefix "" is mapped to URI ""]
[Namespace: prefix "xml" is mapped to URI "http://www.w3.org/XML/1998/namespace"]
[Namespace: prefix "xsi" is mapped to URI "xsi_uri"]
Thus, index 0 is an empty namespace, index 1 is the default XML namespace and finally, index 2 is the added namespace for xsi.
Of course, we don't want to hardcode an index for the desired namespace, therefore, we could do the following to cache the desired namespace beforehand:
Namespace xsiNamespace =
root.getNamespacesInScope().stream() // Streams the namespaces in scope
.filter((ns)->ns.getPrefix().equals("xsi")) // Search for a namespace with the xsi prefix
.findFirst() // Stops at the first find
.orElse(namespace); // If nothing was found, returns
// the previously declared 'namespace' object instead.
Using the cached namespace:
// ...
.setAttribute("type", "CharFixed", xsiNamespace)
// ...

Remove xsi:type information from xml/json JAXB?

I am using JAXB to convert my domain-model to XML and JSON representations.
I have Student pojo to convert to XMl/JSON. It has an content property which can be of any data type.
Schema definition for it:
<xs:element name="content" type="xs:anyType" />
Thus the java file generated has Object type for content.
Student.java:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"content"
})
#XmlRootElement(name = "student")
public class Student
extends People
{
................
#XmlElement(required = true)
protected Object content;
}
I marshall using the following code:
Marshall:
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "name-binding.xml");
this.ctx = JAXBContext.newInstance("packagename",
packagename.ObjectFactory.class.getClassLoader(), properties);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE,media-type);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,true);
marshaller.setProperty(MarshallerProperties.JSON_REDUCE_ANY_ARRAYS, true);
StringWriter sw = new StringWriter();
marshaller.marshal(object, sw);
XML:
<student>
<name>Jack n Jones</name>
<content xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">Sid</content>
</student>
xmlns:xsi and xsi:type="xsd:string"> are coming appended in the content element. I don't want this type information in my XML.
Similarly for JSON it adds the type info:
JSON:
{
"name" : "Jack n Jones",
"content" : {
"type" : "string",
"value" : "Sid"
}
}
How can I remove the type information and generate XML/JSON according to it's type at run time. So whatever type is content it get's converted to the type without type information
For example if content is String then XML:
<student>
<name>Jack n Jones</name>
<content>Sid</content>
</student>
Passing an java.lang.Object parameter in and JAXB annotated pojo and having no additionally generated meta information after marshalling is not possible. Since the Object is "unknown" type, it needs to be detected and converted during marshalling process, and the metadata will always be generated by the default marshaller. From this point on, you have three options:
White your custom marshaller or adapter (there are plenty
examples in WEB)
Use String instead of Object (fast and clean
solution)
If you really must use something generic, use
"Element" (https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/XmlAnyElement.html)

Unmarshalling if stream contains collection?

I have two classes at the moment. Customer and CustomerItem, each Customer can contain multiple CustomerItems:
#XmlRootElement(name = "Customer")
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private final String customerNumber;
private final String customerName;
#XmlElementWrapper(name = "customerItems")
#XmlElement(name = "CustomerItem")
private List<CustomerItem> customerItems;
...
Via REST we can get a List<Customer>, which will result in an XML looking like that:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<collection>
<Customer>
// normal values
<customerItems>
<customerItem>
// normal values
</customerItem>
</customerItems>
</Customer>
<Customer>
...
</Customer>
<Customer>
...
</Customer>
</collection>
Now if I want to unmarshal the response I get an error:
javax.xml.bind.UnmarshalException: unexpected element (uri:"",
local:"collection"). Expected elements are
<{}Customer>,<{}CustomerItem>
private List<Customer> getCustomersFromResponse(HttpResponse response)
throws JAXBException, IllegalStateException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputStream content = response.getEntity().getContent();
InputStreamReader reader = new InputStreamReader(content);
java.util.List<Customer> unmarshal = (List<Customer>) jaxbUnmarshaller.unmarshal(reader);
return unmarshal;
}
Now I know why it's not working, obviously Jaxb expects Customer to be the root element, but now find a collection (which seems to be a default value when a List gets returned?).
A workaround would be to create a new Customers class which contains a list of customer and make it the root element, but actually I wouldn't want a new class.
There must be a way to tell jaxb that I have a list of the classes I want to get and that he should look inside the collection tag or something like that?!
I see here two ways.
1) Create special wrapper class with #XmlRootElement(name = "collection") and set it against unmarshaller.
2) Another way - split input xml into smaller one using simple SAX parser implementation and then parse each fragment separately with JAXB (see: Split 1GB Xml file using Java).
I don't think that you can simply tell JAXB: parse me this xml as set of elements of type XXX.

jdom removes duplicate namespace declaration (xmloutputter)

jdom seems to remove duplicate namespace declarations. This is a problem when a XML document is embedded into another XML structure, such as for example in the OAI-PHM (open archive initiative). This can be a problem when the surrounding xml is only a container and the embedded document gets extracted later.
Here is some code. The embedded xml is contained in the string with the same name. It declares the xsi namespace. We construct a jdom container, also declaring the xsi namespace. We parse and embed the string. When we print the whole thing the inner xsi namepsace is gone.
public static final Namespace OAI_PMH= Namespace.getNamespace( "http://www.openarchives.org/OAI/2.0/");
public static final Namespace XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
public static final String SCHEMA_LOCATION = "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd";
public static final String ROOT_NAME = "OAI-PMH";
String embeddedxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <myxml xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\""
+ "http://www.isotc211.org/2005/gmd"
+ " http://www.ngdc.noaa.gov/metadata/published/xsd/schema/gmd/gmd.xsd"
+ " http://www.isotc211.org/2005/gmx"
+ " http://www.ngdc.noaa.gov/metadata/published/xsd/schema/gmx/gmx.xsd\">\""
+ "</myxml>";
// loadstring omitted (parse embeddedxml into jdom)
Element xml = loadString(embeddedxml ,false);
Element root = new Element(ROOT_NAME, OAI_PMH);
root.setAttribute("schemaLocation", SCHEMA_LOCATION, XSI);
// insert embedded xml into container structure
root.addContent(xml);
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
// will see that the xsi namespace declaration from embeddedxml is gone
out.output(root,System.out);
I think that XMLoutputter is responsible for this behaviour. Any hints how I can make it preserve the duplicate namepspace?
thanks
Kurt
Something is missing in your code: The declaration of final static String ROOT_NAME is not shown and Element xml ist not used after initialization.
If ROOT_NAME is initialized with "myxml" somewhere else, then the solution to your problem is, that you just don't add the xml element to your document, and the result looks as if you did so.

#xmlschema jaxb package-info.java compilation error

I'm trying to use annotations at package level but I get compilation erros from Eclipse.
I have a class Head with the following package/annotation:
#javax.xml.bind.annotation.XmlSchema (
xmlns = {
#javax.xml.bind.annotation.XmlNs(prefix = "com",
namespaceURI="http://es.indra.transporte.common"),
#javax.xml.bind.annotation.XmlNs( namespaceURI="http://www.w3.org/2001/XMLSchema")
},
namespace = "http://es.indra.transporte.common",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
attributeFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package es.indra.transporte.central.thalesinterface.common.beans;
I have created a package-info.java in es.indra.transporte.central.thalesinterface.common.beans folder with the above code but I'm still getting the compilation error
Package annotations must be in file package-info.java
in Head class. I'm using jdk6.
The only problem I got when trying to compile your package info was that the #XmlNs annotation was missing the prefix property.
This:
#javax.xml.bind.annotation.XmlNs( namespaceURI="http://www.w3.org/2001/XMLSchema")
Should be:
#javax.xml.bind.annotation.XmlNs(prefix="xsd", namespaceURI="http://www.w3.org/2001/XMLSchema")
The following corrected code should compile:
#javax.xml.bind.annotation.XmlSchema (
xmlns = {
#javax.xml.bind.annotation.XmlNs(prefix = "com",
namespaceURI="http://es.indra.transporte.common"),
#javax.xml.bind.annotation.XmlNs(prefix="xsd", namespaceURI="http://www.w3.org/2001/XMLSchema")
},
namespace = "http://es.indra.transporte.common",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
attributeFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package es.indra.transporte.central.thalesinterface.common.beans;
For an example see:
http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html

Categories

Resources