Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Guava's Optional with @XmlAttribute

Tags:

java

xml

jaxb

guava

I would like to setup a JAXB-annotated Java class to generate some XML in the following format:

<page refId="0001">
    <title>The title of my page</title>
</page>

The "refId" field is optional, so I'd like to use Guava's Optional construct to reference the string in memory. I see Using generic @XmlJavaTypeAdapter to unmarshal wrapped in Guava's Optional, which gives a thorough example if you're using an element (even if that wasn't the original question), but how would you set up the annotations for an XML attribute?

Here's what I have so far:

@XmlRootElement(name="page")
public final class Page {
    @XmlAttribute
    @XmlJavaTypeAdapter(OptionalAdapter.class)
    private Optional<String> refId;

    @XmlElement
    private String title;

    ... getters/setters, default constructor, etc.
}

And OptionalAdapter is a simple XmlAdapter:

public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {

    @Override
    public Optional<T> unmarshal(T v) throws Exception {
        return Optional.fromNullable(v);
    }

    @Override
    public T marshal(Optional<T> v) throws Exception {
        if (v == null || !v.isPresent()) {
            return null;
        } else {
            return v.get();
        }
    }
}

When I try to load up a unit test against the above code, it fails instantly during initialization, but if I change the annotation to @XmlElement, the test will run and pass, but obviously sets the refId as a child element instead of an attribute.

Thanks in advance!

like image 779
unknowngalaxy Avatar asked Apr 14 '14 22:04

unknowngalaxy


1 Answers

Xml-attribute can have only simple type (like String, Integer etc.), so you cann't use OptionalAdapter<T>.
If your field has type String then adapter should have type OptionalAdapter<String>.
You can do in next way:
- create additional class, and use is as XmlAdapter

   public final class StringOptionalAdapter extends OptionalAdapter<String>
   {
   }  

Page.java

   @XmlAttribute
   @XmlJavaTypeAdapter(StringOptionalAdapter.class)
   private Optional<String> refId;
like image 112
Ilya Avatar answered Oct 11 '22 08:10

Ilya