I need to make a Rest POST to a service that returns either a <job/>
or an <exception/>
and always status code 200
. (lame 3rd party product!).
I have code like:
Job job = getRestTemplate().postForObject(url, postData, Job.class);
And my applicationContext.xml looks like:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller"/>
<property name="unmarshaller" ref="jaxbMarshaller"/>
</bean>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>domain.fullspec.Job</value>
<value>domain.fullspec.Exception</value>
</list>
</property>
</bean>
When I try to make this call and the service fails, I get:
Failed to convert value of type 'domain.fullspec.Exception' to required type 'domain.fullspec.Job'
In the postForObject() call, I am asking for a Job.class and not getting one and it is getting upset.
I am thinking I need to be able to do something along the lines of:
Object o = getRestTemplate().postForObject(url, postData, Object.class);
if (o instanceof Job.class) {
...
else if (o instanceof Exception.class) {
}
But this doesnt work because then JAXB complains that it doesnt know how to marshal to Object.class - not surprisingly.
I have attempted to create subclass of MarshallingHttpMessageConverter and override readFromSource()
protected Object readFromSource(Class clazz, HttpHeaders headers, Source source) {
Object o = null;
try {
o = super.readFromSource(clazz, headers, source);
} catch (Exception e) {
try {
o = super.readFromSource(MyCustomException.class, headers, source);
} catch (IOException e1) {
log.info("Failed readFromSource "+e);
}
}
return o;
}
Unfortunately, this doesnt work because the underlying inputstream inside source has been closed by the time I retry it.
Any suggestions gratefully received,
Tom
UPDATE: I have got this to work by taking a copy of the inputStream
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) {
InputStream is = ((StreamSource) source).getInputStream();
// Take a copy of the input stream so we can use it for initial JAXB conversion
// and if that fails, we can try to convert to Exception
CopyInputStream copyInputStream = new CopyInputStream(is);
// input stream in source is empty now, so reset using copy
((StreamSource) source).setInputStream(copyInputStream.getCopy());
Object o = null;
try {
o = super.readFromSource(clazz, headers, source);
// we have failed to unmarshal to 'clazz' - assume it is <exception> and unmarshal to MyCustomException
} catch (Exception e) {
try {
// reset input stream using copy
((StreamSource) source).setInputStream(copyInputStream.getCopy());
o = super.readFromSource(MyCustomException.class, headers, source);
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return o;
}
CopyInputStream is taken from http://www.velocityreviews.com/forums/t143479-how-to-make-a-copy-of-inputstream-object.html, i'll paste it here.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class CopyInputStream
{
private InputStream _is;
private ByteArrayOutputStream _copy = new ByteArrayOutputStream();
/**
*
*/
public CopyInputStream(InputStream is)
{
_is = is;
try
{
copy();
}
catch(IOException ex)
{
// do nothing
}
}
private int copy() throws IOException
{
int read = 0;
int chunk = 0;
byte[] data = new byte[256];
while(-1 != (chunk = _is.read(data)))
{
read += data.length;
_copy.write(data, 0, chunk);
}
return read;
}
public InputStream getCopy()
{
return (InputStream)new ByteArrayInputStream(_copy.toByteArray());
}
}
@Tom: I don't think creating a custom MarshallingHttpMessageConverter will do you any good. The built-in converter is returning you the right class (Exception class) when the service fails, but it is the
RestTemplate
that doesn't know how to return Exception class to the callee because you have specified the response type as Job class.I read the RestTemplate source code, and you are currently calling this API:-
As you can see, it returns type T based on your response type. What you probably need to do is to subclass
RestTemplate
and add a newpostForObject()
API that returns an Object instead of type T so that you can perform theinstanceof
check on the returned object.UPDATE
I have been thinking about the solution for this problem, instead of using the built-in
RestTemplate
, why not write it yourself? I think that is better than subclassingRestTemplate
to add a new method.Here's my example... granted, I didn't test this code but it should give you an idea:-
If there are circumstances where you want to reuse some of the APIs from
RestTemplate
, you can build an adapter that wraps your custom implementation and reuseRestTemplate
APIs without actually exposingRestTemplate
APIs all over your code.For example, you can create an adapter interface, like this:-
The concrete custom rest template looks something like this:-
I still think this approach is much cleaner than subclassing
RestTemplate
and you have more control on how you want to handle the results from the web service calls.While trying to solve the same issue, I found the following solution.
I'm using the a default instance of RestTemplate, and generated files using xjc. The converter that is invoked is Jaxb2RootElementHttpMessageConverter.
It turns out that the converter returns the "real" type in case the input class is annotated with XmlRootElement annotation. That is, the method
may return an Object that is not an instance of clazz, given that clazz has an XmlRootElement annotation present. In this case, clazz is only used to create an unmarshaller that will unmarshall clazz.
The following trick solves the problem: If we define
and pass XmlResponse.class to postForObject(...), than the response will be Exception or Job.
This is somewhat of a hack, but it solves the problem of postForObject method not being able to return more than one object class.