Reputation: 2088
I have an XmlAdapter to marshal associated objects in a class to their respective REST URI's:
public class AirportAdapter extends XmlAdapter<URI, Airport> {
@Override
public URI marshal(Airport airport) throws Exception {
return UriBuilder.fromResource(AirportsResource.class).path(AirportsResource.class,
"getAirportResource").build(airport.getId());
}
This, however, yields a relative URL (/airports/1) that is unable to unmarshal the URI into an Airport
object (obviously):
@Override
public Airport unmarshal(URI uri) throws Exception {
// Does work, but not desirable
return JAXB.unmarshal("http://localhost/resources" + uri, Airport.class)
// Does not work
return JAXB.unmarshal(uri, Airport.class);
}
}
I need the UriBuilder
to build an absolute path (http://localhost/resources/airports/1) and I understand I can do this using the UriInfo
class, but I can't inject it into the adapter because it's not a resource. When I prepend the URI with the protocol, host and resources path, the unmarshalling does work. What way is there to get the UriBuilder to build an absolute path without preprending it myself?
Update
I figured if I create a JAXB context myself:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo:com.acme.bar" );
Unmarshaller u = jc.createUnmarshaller();
and set the adapters on the unmarshaller myself, passing the entity manager to grab the correct object from the database instead of umarshalling via the URI, would these be used by the framework as well or does it create new instances himself, rendering this approach mute?
Upvotes: 1
Views: 2598
Reputation: 149017
If you set an instance of an XmlAdapter
on a Marshaller
/Unmarshaller
then that instance of the XmlAdapter
will be used in all places that have been annotated with @XmlJavaTypeAdapter
to use that class.
In a JAX-RS environment such as Jersey, you can set this up using a MessageBodyReader
/MessageBodyWriter
.
Upvotes: 1