开发者

How to use Spring RestTemplate and JAXB marshalling on a URL that returns multiple types of XML

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());

    Obje开发者_StackOverflow中文版ct 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());
}
}


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

protected Object readFromSource(Class clazz, HttpHeaders headers, Source source)

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

@XmlRootElement()
@XmlSeeAlso({ Exception.class, Job.class })
public static abstract class XmlResponse {}

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.


@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:-

public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
    HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(request, responseType);
    HttpMessageConverterExtractor<T> responseExtractor =
            new HttpMessageConverterExtractor<T>(responseType, getMessageConverters());
    return execute(url, HttpMethod.POST, requestCallback, responseExtractor);
}

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 new postForObject() API that returns an Object instead of type T so that you can perform the instanceof 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 subclassing RestTemplate to add a new method.

Here's my example... granted, I didn't test this code but it should give you an idea:-

// reuse the same marshaller wired in RestTemplate
@Autowired
private Jaxb2Marshaller jaxb2Marshaller;

public Object genericPost(String url) {
    // using Commons HttpClient
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    // add your data here
    method.addParameter("data", "your-data");

    try {
        int returnCode = client.executeMethod(method);

        // status code is 200
        if (returnCode == HttpStatus.SC_OK) {
            // using Commons IO to convert inputstream to string
            String xml = IOUtil.toString(method.getResponseBodyAsStream());
            return jaxb2Marshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));
        }
        else {
            // handle error
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
    finally {
        method.releaseConnection();
    }

    return null;
}

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 reuse RestTemplate APIs without actually exposing RestTemplate APIs all over your code.

For example, you can create an adapter interface, like this:-

public interface MyRestTemplateAdapter {
    Object genericPost(String url);

    // same signature from RestTemplate that you want to reuse
    <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables);
}

The concrete custom rest template looks something like this:-

public class MyRestTemplateAdapterImpl implements MyRestTemplateAdapter {
    @Autowired
    private RestTemplate    restTemplate;

    @Autowired
    private Jaxb2Marshaller jaxb2Marshaller;

    public Object genericPost(String url) {
        // code from above
    }

    public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) {
        return restTemplate.postForObject(url, request, responseType);
    }
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜