I would like to know how I can implement optional attributes within XStream.
Here is the XML:
<AttributeValues>
<AttributeValue attributeId='id01' languageId='en'>20</AttributeValue>
<AttributeValue attributeId='id02'>99</AttributeValue>
<AttributeValue attributeId='id03' languageId='en'78</AttributeValue>
<AttributeValue attributeId='id04' languageId='en'>14</AttributeValue>
<AttributeValue attributeId='id05'>9</AttributeValue>
</AttributeValues>
After the parsing process, not every 'AttributeValue' item has a languageId.
XStream sets such empty values to 'null'. But I would like to have it as an empty string "".
How do I implement this?
You can achieve your goal using custom Converter class.
There will be a bit of guessing here since you haven't posted code for AttributeValues and AttributeValue class. I will use following classes:
AttributeValues class:
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import java.util.ArrayList;
import java.util.List;
#XStreamAlias("AttributeValues")
public class AttributeValues
{
#XStreamImplicit(itemFieldName="AttributeValue")
public List<AttributeValue> Values;
public AttributeValues()
{
Values = new ArrayList<AttributeValue>();
}
public void add(String id, String lg, String value)
{
AttributeValue item = new AttributeValue();
item.attributeId = id;
item.languageId = lg;
item.value = value;
Values.add(item);
}
}
AttributeValue class:
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
public class AttributeValue
{
#XStreamAsAttribute
public String attributeId;
#XStreamAsAttribute
public String languageId;
public String value;
}
And here is AttributeValueConverter class:
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public class AttributeValueConverter implements Converter
{
public boolean canConvert(Class clazz) {
return AttributeValue.class == clazz;
}
public void marshal(Object object, HierarchicalStreamWriter hsw, MarshallingContext mc) {
AttributeValue av = (AttributeValue) object;
hsw.addAttribute("attributeId", av.attributeId);
hsw.addAttribute("languageId", av.languageId);
hsw.setValue(av.value);
}
public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc) {
AttributeValue av = new AttributeValue();
av.attributeId = hsr.getAttribute("attributeId");
av.languageId = hsr.getAttribute("languageId");
if (av.languageId == null) av.languageId = "";
av.value = hsr.getValue();
return av;
}
}
Serialization:
AttributeValues obj = new AttributeValues();
obj.add("id01", "en", "20");
XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.registerConverter(new AttributeValueConverter());
String s = xstream.toXML(obj);
Unserialization:
XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.registerConverter(new AttributeValueConverter());
AttributeValues newobj = (AttributeValues)xstream.fromXML(s);
Related
I am trying to simplify the conversion of POJO to XML, but I am facing issues with Class field attributes.
Consider the following XML files
<cat>
<displayTexts>
<displayText language="en">12</displayText>
<displayText language="en">23</displayText>
</displayTexts>
</cat>
And
I have a class
#XmlRootElement(name = "cat")
public class Category{
List<Integer> list;
public List<Integer> getList() {
return list;
}
#XmlElementWrapper(name = "displayTexts")
#XmlElement(name = "displayText")
public void setList(List<Integer> list) {
this.list = list;
}
}
How can I write an adaptor which will produce XML mentioned as above?
Right now it will produce something like below xml ::
<cat>
<displayTexts>
<displayText>12</displayText>
<displayText>23</displayText>
</displayTexts>
</cat>
Note:: I am not allowed to use MoXy. And I know I can achieve this by writing a different class. The question is can we write an adaptor so that I can generalize this attribute thing for any class field?
Although I would still recommend, using a class Instead of Integer to use the value for displayText and it's attribute, but still if you want to achieve without any new class, you can give following a shot using #XmlAnyElement for your displayList and "creating" the xml yourself:
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
#XmlRootElement(name = "cat")
public class Category {
List<Integer> list;
#XmlAnyElement()
#XmlJavaTypeAdapter(MyIntegerAdapter.class)
public List<Integer> getList() {
return list;
}
//#XmlElement(name = "displayText")
public void setList(List<Integer> list) {
this.list = list;
}
public static void main(String[] args) throws Exception {
Category bx = new Category();
List<Integer> lists = Arrays.asList(121, 212);
bx.setList(lists);
JAXBContext jc = JAXBContext.newInstance(Category.class);
MyIntegerAdapter adapter = new MyIntegerAdapter();
Marshaller marrshaller = jc.createMarshaller();
marrshaller.setAdapter(adapter);
marrshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marrshaller.marshal(bx, System.out);
}
}
class MyIntegerAdapter extends XmlAdapter<Element, List<Integer>> {
private DocumentBuilder documentBuilder;
public MyIntegerAdapter() {
}
private DocumentBuilder getDocumentBuilder() throws Exception {
// Lazy load the DocumentBuilder as it is not used for unmarshalling.
if (null == documentBuilder) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
documentBuilder = dbf.newDocumentBuilder();
}
return documentBuilder;
}
#Override
public Element marshal(List<Integer> lists) throws Exception {
if (null == lists) {
return null;
}
Document document = getDocumentBuilder().newDocument();
Element element = document.createElement("displayTexts");
for (int value : lists) {
Element displayText = document.createElement("displayText");
System.out.println("value.." + value);
displayText.setTextContent(value + "");
displayText.setAttribute("Lang", "en");
element.appendChild(displayText);
}
return element;
}
#Override
public List<Integer> unmarshal(Element v) throws Exception {
//TODO
throw new UnsupportedOperationException();
}
}
I have the following classes with jax-ws webservice;
Interface Class (myserviceInt.java);
#WebService(name="myservice")
#SOAPBinding(style=Style.RPC)
public interface myserviceInt {
#WebMethod(action="urn:OutIn", operationName="ACCT")
public String getACCT(
#WebParam(partName="Prod1")String prod1,
#WebParam(partName="Prod2")String prod2);
}
Implementation Class (myserviceImpl.java);
#WebService(endpointInterface = "path.to.webservice.myserviceInt", portName="acct", serviceName="acctservice", targetNamespace="http://demo.acctservice.com/")
public class myserviceImpl implements myserviceInt {
#Override
public String getACCT(String prod1, String prod1){
Other codes
String id = "25";
String description = "The Third Product"
ACCTResponse acct = new ACCTResponse();
acct.setId(id);
acct.setDescription(description);
String XMLstring = acct.ACCTResponseBeanToXML(acct);
return XMLstring;
}
}
ACCTResponse Class (ACCTResponse.java);
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name="ACCTResponse")
public class ACCTResponse {
#XmlElement(name = "ID")
private String id;
#XmlElement(name = "Description")
private String description;
... their setters and getters;
}
The Marshaller Class (ACCTUtil.java);
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import path.to.responseclass.ACCTResponse;
public class ACCTUtil {
public static String ACCTResponseBeanToXML(ACCTResponse acct)
{
String responseStr = null;
try
{
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(ACCTResponse.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(acct, writer);
responseStr = writer.toString();
int xmlHeaderIndex = responseStr.indexOf("?>");
if(xmlHeaderIndex > 0)
responseStr = responseStr.substring(xmlHeaderIndex + 2, responseStr.length());
}
catch(Exception ex){
ex.printStackTrace();
}
return responseStr;
}
}
every other libraries needed were left out to save time. I also have the package-info.java in the respective path for the ACCTResponse.java to add the required response namespaceURI and prefix.
Now, I got the following as response after Marshalling as described above;
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:ACCTResponse xmlns:ns2="http://demo.acctservice.com/">
<return><![CDATA[<net:ACCTResponse xmlns:net="http://demo.acctservice.com/">
<net:ID>25</net:ID>
<net:Description>The Third Product</net:Description>
</net:ACCTResponse>]]></return>
</ns2:ACCTResponse>
</S:Body>
</S:Envelope>
The response I want to achieve for a consumer of this webservice that have a fixed client is this;
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org /soap/envelope/">
<saop:Body>
<net:ACCTResponse xmlns:net="http://demo.acctservice.com/">
<net:ID>25</net:ID>
<net:Description>The Third Product</net:Description>
</net:ACCTResponse>
</soapenv:Body>
</soapenv:Envelope>
What modifications/manipulations do I need, to achieve this response from my codes. Thanks.
This seems simple, but I must be missing something. All I am trying to do is unmarshall a JSON array. I have code that works when the JSON is a simple object, but when I make it an array (ie..surround JSON with []), it fails. Here is the sample json, domain class, unmarshalling code, and exception. Any help will be greatly appreciated.
Sample JSON:
[{"CreateIndex":24988,"ModifyIndex":132476,"LockIndex":0,"Key":"Redirector","Flags":0}
]
Domain:
package eclipselink.example.moxy.json.simple.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.base.Optional;
import com.google.common.io.BaseEncoding;
import com.orbitz.consul.model.kv.ImmutableValue;
import com.orbitz.consul.util.UnsignedLongDeserializer;
#org.immutables.value.Value.Immutable
#JsonDeserialize(as = ImmutableValue.class)
#JsonSerialize(as = ImmutableValue.class)
#JsonIgnoreProperties(ignoreUnknown = true)
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class MyValue {
#XmlAttribute
private long createIndex;
#XmlAttribute
private long modifyIndex;
#XmlAttribute
private long lockIndex;
#XmlAttribute
private String key;
#XmlElement
private long flags;
#XmlElement(nillable = true)
private Optional<String> value;
#XmlElement
private Optional<String> session;
#JsonProperty("CreateIndex")
public long getCreateIndex() {
return createIndex;
}
#JsonProperty("ModifyIndex")
public long getModifyIndex() {
return modifyIndex;
}
#JsonProperty("LockIndex")
public long getLockIndex() {
return lockIndex;
}
#JsonProperty("Key")
public String getKey() {
return key;
}
#JsonProperty("Flags")
#JsonDeserialize(using=UnsignedLongDeserializer.class)
public long getFlags() {
return flags;
}
#JsonProperty("Value")
public Optional<String> getValue() {
return value;
}
#JsonProperty("Session")
public Optional<String> getSession() {
return session;
}
#JsonIgnore
#org.immutables.value.Value.Lazy
public Optional<String> getValueAsString() {
if (getValue() != null && getValue().isPresent()) {
return Optional.of(
new String(BaseEncoding.base64().decode(getValue().get()))
);
} else {
return Optional.absent();
}
}
}
Unmarshall code:
public class Main_JSON_redirector {
private static final String INPUT_XML = "META-INF/input.xml";
private static final String INPUT_JSON_URL = "http://192.168.85.186:8500/v1/kv/Redirector";
private static final File INPUT_JSON_FILE = new File("C:/Users/dnance/EclipseLink-examples/moxy/json-simple/src/main/resources/META-INF/redirector.json");
public static void main(String[] args) throws Exception {
System.out.println();
System.out.println("Running EclipseLink MOXy Simple MAIN_JSON Example");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
JAXBContext jc = JAXBContext.newInstance(new Class[] {MyValue.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
StreamSource source = new StreamSource(INPUT_JSON_FILE);
JAXBElement<MyValue[]> jaxbElement = unmarshaller.unmarshal(source, MyValue[].class);
MyValue[] value = jaxbElement.getValue();
System.out.println("value: " + value[0].getValueAsString());
...
Exception:
Running EclipseLink MOXy Simple MAIN_JSON Example
Exception in thread "main" javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class [Leclipselink.example.moxy.json.simple.model.MyValue; was not found in the project. For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.]
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1072)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:341)
at eclipselink.example.moxy.json.simple.Main_JSON_redirector.main(Main_JSON_redirector.java:58)
Caused by: Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class [Leclipselink.example.moxy.json.simple.model.MyValue; was not found in the project. For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.
at org.eclipse.persistence.exceptions.XMLMarshalException.descriptorNotFoundInProject(XMLMarshalException.java:154)
at org.eclipse.persistence.internal.oxm.Context$ContextState.getSession(Context.java:137)
at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:798)
at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:1)
at org.eclipse.persistence.internal.oxm.Context.getSession(Context.java:458)
at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:366)
at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:1)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:837)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:710)
at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:643)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
You just need to specify type class instead of array class in unmarshal method, E.g.
Collection<MyValue> myValues = (Collection<MyValue>) unmarshaller.unmarshal(source, MyValue.class).getValue();
Since you have unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); it just works. Without it unmarshal returns JAXBElement<Collection<JAXBElement>>.
The answer to my question
JaxB reference resolving
led me to further pursue the details of the issue regarding the use of XmlSeeAlso, XmlElementReference and the specification of classes involved in JaxbContext.newInstance.
I started with trying to answer the question:
Is it possible to #XmlSeeAlso on a class without no-args constructor which has #XmlJavaTypeAdapter?
i created the Junit test below. To do so I came accross:
#XmlJavaTypeAdapter w/ Inheritance
#XmlSeeAlso alternative
In this state the code is compilable and runs - it marshals o.k. but does not umarshal as expected.
The marshal result is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Message>
<BasicInfo ref="id001"/>
</Message>
Unmarshalling does not create a BasicInfo as would be expected from the code in the Adapter:
public BasicInfo unmarshal(BasicInfoRef info) throws Exception {
BasicInfo binfo=new BasicInfo();
binfo.id=info.ref;
return binfo;
}
I find this all very confusing - things seem to be somewhat contradictory and mostly do not work as I'd expect regarding the JaxB settings involved. Most combinations do not work, those that do work do not give the full result yet. I assume that is also depending on the version and implementation being used.
What nees to be done to get this working?
What is a minimal set of XmlElementRef,XmlSeeAlso and JaxbContext newInstance referencing of the necessary classes?
How can I check which JaxB Implementation is being used? I am using EclipseLink 2.3.2? and I'm not sure whether this uses MoxY or not.
Update:
after consideration of:
JAXB xsi:type subclass unmarshalling not working
http://www.java.net/node/654579
http://jaxb.java.net/faq/#jaxb_version
http://www.eclipse.org/eclipselink/documentation/2.4/moxy/type_level003.htm
Can JAXB marshal by containment at first then marshal by #XmlIDREF for subsequent references?
The modified code below is close to what is intended.
Errors that showed up while trying were:
javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.SAXException2: unable to marshal type "com.bitplan.storage.jaxb.TestRefId$BasicInfo$BasicInfoRef" as an element because it is missing an #XmlRootElement annotation]
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323)
The code has quite a few comments which can be commented in and out to find out what happens if one tries ...
I still have no clue what the optimal solution would be to avoid superfluous annotations.
modified code:
package com.bitplan.storage.jaxb;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue;
import org.junit.Test;
/**
* Test the Reference/Id handling for Jaxb
*
* #author wf
*
*/
public class TestRefId {
#XmlDiscriminatorNode("#reforid")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RefOrId.Adapter.class)
public static class RefOrId {
#XmlAttribute(name = "reforid")
public String reforid;
public RefOrId() {
}
#XmlAttribute
public String id;
#XmlAttribute
public String ref;
public static class Adapter extends XmlAdapter<RefOrId, RefOrId> {
#Override
public RefOrId marshal(RefOrId idref) throws Exception {
if (idref == null)
return null;
System.out.println("marshalling " + idref.getClass().getSimpleName()
+ " reforid:" + idref.reforid);
if (idref instanceof Ref)
return new Id(((Ref) idref).ref);
return idref;
}
#Override
public RefOrId unmarshal(RefOrId idref) throws Exception {
System.out.println("unmarshalling " + idref.getClass().getSimpleName()
+ " reforid:" + idref.reforid);
return idref;
}
}
}
#XmlDiscriminatorValue("id")
#XmlAccessorType(XmlAccessType.FIELD)
public static class Id extends RefOrId {
public Id() {
reforid = "id";
}
public Id(String pId) {
this();
this.id = pId;
}
}
#XmlDiscriminatorValue("ref")
#XmlAccessorType(XmlAccessType.FIELD)
public static class Ref extends RefOrId {
public Ref() {
reforid = "ref";
}
public Ref(String pRef) {
this();
this.ref = pRef;
}
}
/*
* https://stackoverflow.com/questions/8292427/is-it-possible-to-xmlseealso-on-a
* -class-without-no-args-constructor-which-has
*/
#XmlRootElement(name = "BasicInfo")
public static class BasicInfo {
public BasicInfo() {
};
public BasicInfo(String pId, String pInfo) {
this.id = new Id(pId);
this.basic = pInfo;
}
// #XmlTransient
public RefOrId id;
public String basic;
}
#XmlRootElement(name = "SpecificInfoA")
// #XmlJavaTypeAdapter(BasicInfo.Adapter.class)
public static class SpecificInfoA extends BasicInfo {
public SpecificInfoA() {
};
public SpecificInfoA(String pId, String pInfo, String pInfoA) {
super(pId, pInfo);
infoA = pInfoA;
}
public String infoA;
}
#XmlRootElement(name = "Message")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlSeeAlso({ SpecificInfoA.class, BasicInfo.class })
public static class Message {
public Message() {
};
public Message(BasicInfo pBasicInfo) {
basicInfos.add(pBasicInfo);
}
// #XmlJavaTypeAdapter(BasicInfo.Adapter.class)
// #XmlElement(name="basicInfo",type=BasicInfoRef.class)
#XmlElementWrapper(name = "infos")
#XmlElement(name = "info")
public List<BasicInfo> basicInfos = new ArrayList<BasicInfo>();
}
/**
* marshal the given message
*
* #param jaxbContext
* #param message
* #return - the xml string
* #throws JAXBException
*/
public String marshalMessage(JAXBContext jaxbContext, Message message)
throws JAXBException {
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(message, sw);
String xml = sw.toString();
return xml;
}
/**
* test marshalling and umarshalling a message
*
* #param message
* #throws JAXBException
*/
public void testMessage(Message message) throws JAXBException {
#SuppressWarnings("rawtypes")
Class[] classes = { Message.class, SpecificInfoA.class, BasicInfo.class }; // BasicInfo.class,};
// https://stackoverflow.com/questions/8318231/xmlseealso-alternative/8318490#8318490
// https://stackoverflow.com/questions/11966714/xmljavatypeadapter-not-being-detected
JAXBContext jaxbContext = JAXBContext.newInstance(classes);
String xml = marshalMessage(jaxbContext, message);
System.out.println(xml);
Unmarshaller u = jaxbContext.createUnmarshaller();
Message result = (Message) u.unmarshal(new StringReader(xml));
assertNotNull(result);
assertNotNull(message.basicInfos);
for (BasicInfo binfo : message.basicInfos) {
RefOrId id = binfo.id;
assertNotNull(id);
System.out.println("basicInfo-id " + id.getClass().getSimpleName()
+ " for reforid " + id.reforid);
// assertEquals(message.basicInfo.id, result.basicInfo.id);
}
xml = marshalMessage(jaxbContext, result);
System.out.println(xml);
}
/**
* switch Moxy
*
* #param on
* #throws IOException
*/
public void switchMoxy(boolean on) throws IOException {
File moxySwitch = new File(
"src/test/java/com/bitplan/storage/jaxb/jaxb.properties");
if (on) {
PrintWriter pw = new PrintWriter(new FileWriter(moxySwitch));
pw.println("javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory");
pw.close();
} else {
moxySwitch.delete();
}
}
#Test
public void testStackOverflow8292427() throws JAXBException, IOException {
boolean[] moxyOnList = { false };
for (boolean moxyOn : moxyOnList) {
switchMoxy(moxyOn);
System.out.println("Moxy used: " + moxyOn);
Message message = new Message(new BasicInfo("basicId001",
"basicValue for basic Info"));
message.basicInfos.add(new SpecificInfoA("specificId002",
"basicValue for specific Info", "specific info"));
message.basicInfos.add(new SpecificInfoA("specificId002",
"basicValue for specific Info", "specific info"));
testMessage(message);
}
}
}
This is the Junit Test as mentioned above (before update):
package com.bitplan.storage.jaxb;
import static org.junit.Assert.*;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import org.junit.Test;
// Test the Reference/Id handling for Jaxb
public class TestRefId {
/*
* https://stackoverflow.com/questions/8292427/is-it-possible-to-xmlseealso-on-a-class-without-no-args-constructor-which-has
*/
#XmlRootElement(name="BasicInfo")
#XmlJavaTypeAdapter(BasicInfo.Adapter.class)
public static class BasicInfo {
#XmlRootElement(name="BasicInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public static class BasicInfoRef {
#XmlAttribute(name = "ref")
public String ref;
}
public static class Adapter extends XmlAdapter<BasicInfoRef,BasicInfo>{
#Override
public BasicInfoRef marshal(BasicInfo info) throws Exception {
BasicInfoRef infoRef = new BasicInfoRef();
infoRef.ref=info.id;
return infoRef;
}
#Override
public BasicInfo unmarshal(BasicInfoRef info) throws Exception {
BasicInfo binfo=new BasicInfo();
binfo.id=info.ref;
return binfo;
}
} // Adapter
public String id;
public String basic;
}
#XmlJavaTypeAdapter(BasicInfo.Adapter.class)
public static class SpecificInfoA extends BasicInfo {
public String infoA;
}
#XmlRootElement(name="Message")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlSeeAlso({SpecificInfoA.class,BasicInfo.class})
public static class Message {
// https://stackoverflow.com/questions/3107548/xmljavatypeadapter-w-inheritance
#XmlElementRefs({
#XmlElementRef(name="basic", type=BasicInfo.class),
// #XmlElementRef(name="infoA", type=SpecificInfoA.class)
})
public BasicInfo basicInfo;
}
#Test
public void testStackOverflow8292427() throws JAXBException {
Message message=new Message();
SpecificInfoA info=new SpecificInfoA();
info.id="id001";
info.basic="basicValue";
info.infoA="infoAValue";
message.basicInfo=info;
#SuppressWarnings("rawtypes")
Class[] classes= {Message.class,SpecificInfoA.class,BasicInfo.class,BasicInfo.BasicInfoRef.class}; // BasicInfo.class,};
// https://stackoverflow.com/questions/8318231/xmlseealso-alternative/8318490#8318490
JAXBContext jaxbContext = JAXBContext.newInstance(classes);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(message, sw);
String xml=sw.toString();
System.out.println(xml);
Unmarshaller u = jaxbContext.createUnmarshaller();
Message result = (Message) u.unmarshal(new StringReader(xml));
assertNotNull(result);
assertNotNull("basicInfo should not be null",result.basicInfo);
assertEquals("id001",result.basicInfo.id);
}
}
I use REST and i was wondering if i can tell jaxb to insert a string field "as-it-is" into the outgoing xml.
Certainly i count unpack it before returning, but i would like to save this step.
#XmlRootElement(name="unnestedResponse")
public class Response{
#Insert annotation here ;-)
private String alreadyXml;
private int otherDate; ...
}
Is there a possability to tell JAXB to just use the String as it is without escapting? I want that the client does not have to parse my response and then parse this field.
greetings,
m
You can use the #XmlAnyElement and specify a DomHandler to keep a portion of the XML document as a String.
Customer
import javax.xml.bind.annotation.*;
#XmlRootElement
public class Customer {
private String bio;
#XmlAnyElement(BioHandler.class)
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
}
BioHandler
import java.io.*;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.*;
public class BioHandler implements DomHandler<String, StreamResult> {
private static final String BIO_START_TAG = "<bio>";
private static final String BIO_END_TAG = "</bio>";
private StringWriter xmlWriter = new StringWriter();
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
return new StreamResult(xmlWriter);
}
public String getElement(StreamResult rt) {
String xml = rt.getWriter().toString();
int beginIndex = xml.indexOf(BIO_START_TAG) + BIO_START_TAG.length();
int endIndex = xml.indexOf(BIO_END_TAG);
return xml.substring(beginIndex, endIndex);
}
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = BIO_START_TAG + n.trim() + BIO_END_TAG;
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
For More Information
http://blog.bdoughan.com/2011/04/xmlanyelement-and-non-dom-properties.html
Following bdoughan's answer did not work for me as I encountered errors during marshalling when the text contained the '& character (e.g. in URLs or when using HTML entities such as e.g. " ").
I was able to resolve this by changing the custom DomHandler's marshal method to
public Source marshal(String et, ValidationEventHandler veh) {
Node node = new SimpleTextNode(et);
return new DOMSource(node);
}
where SimpleTextNode implements the Node interface as follows:
class SimpleTextNode implements Node {
String nodeValue = "";
#Override
public SimpleTextNode(String nodeValue) {
this.nodeValue = nodeValue;
}
#Override
public short getNodeType() {
return TEXT_NODE;
}
// the remaining methods of the Node interface are not needed during marshalling
// you can just use the code template of your IDE...
...
}
PS: I would have loved to leave this as a comment to bdoughan's answer, but unfortunately I have way too little reputation :-(