如何在返回多种类型XML的URL上使用Spring RestTemplate和JAXB编组

时间:2011-03-02 16:53:28

标签: java jaxb resttemplate

我需要对返回<job/><exception/>以及状态代码200的服务进行Rest POST。 (蹩脚的第三方产品!)。

我的代码如下:

Job job = getRestTemplate().postForObject(url, postData, Job.class);

我的applicationContext.xml看起来像:

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

当我尝试拨打此电话并且服务失败时,我得到:

 Failed to convert value of type 'domain.fullspec.Exception' to required type 'domain.fullspec.Job'

在postForObject()调用中,我要求一个Job.class而不是一个,它会让人感到不安。

我想我需要能够按照以下方式做点什么:

Object o = getRestTemplate().postForObject(url, postData, Object.class);
if (o instanceof Job.class) {
   ...
else if (o instanceof Exception.class) {
}

但这不起作用,因为JAXB抱怨说它不知道如何编组到Object.class - 这并不奇怪。

我试图创建MarshallingHttpMessageConverter的子类并覆盖readFromSource()

protected Object readFromSource(Class clazz,HttpHeaders header,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;
}

不幸的是,这不起作用,因为我重新尝试时源内的基础输入流已经关闭。

感激地收到任何建议,

汤姆

更新:我通过获取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取自http://www.velocityreviews.com/forums/t143479-how-to-make-a-copy-of-inputstream-object.html,我会将其粘贴到此处。

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

2 个答案:

答案 0 :(得分:5)

在尝试解决同样的问题时,我找到了以下解决方案。

我正在使用RestTemplate的默认实例,并使用xjc生成文件。调用的转换器是Jaxb2RootElementHttpMessageConverter。

事实证明,如果输入类使用XmlRootElement注释进行注释,转换器将返回“real”类型。也就是说,方法

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

可能返回一个不是clazz实例的Object,因为clazz中存在一个XmlRootElement注释。在这种情况下,clazz仅用于创建一个unmarshaller来解组clazz。

以下技巧解决了问题:如果我们定义

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

并将XmlResponse.class传递给postForObject(...),而响应将是Exception或Job。

这有点像黑客,但它解决了postForObject方法无法返回多个对象类的问题。

答案 1 :(得分:4)

@Tom:我不认为创建自定义MarshallingHttpMessageConverter会对你有所帮助。当服务失败时,内置转换器返回正确的类(Exception类),但是RestTemplate不知道如何将Exception类返回给被调用者,因为您已将响应类型指定为工作班。

我阅读了RestTemplate source code,您目前正在调用此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);
}

如您所见,它会根据您的响应类型返回T类型。您可能需要做的是继承RestTemplate并添加一个新的postForObject() API,它返回一个Object而不是T类,以便您可以对返回的对象执行instanceof检查。 / p>

<强>更新

我一直在考虑这个问题的解决方案,而不是使用内置的RestTemplate,为什么不自己编写呢?我认为这比继承RestTemplate以便添加新方法更好。

这是我的例子......授予,我没有测试这段代码,但它应该给你一个想法: -

// 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;
}

如果您希望重用RestTemplate中的某些API,则可以构建一个包装自定义实现并重用RestTemplate API的适配器,而不会实际暴露RestTemplate API遍布你的代码。

例如,您可以创建适配器接口,如下所示: -

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

具体的自定义休息模板如下所示: -

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

我仍然认为这种方法比继承RestTemplate更清晰,并且您可以更好地控制如何处理来自Web服务调用的结果。