关于Rop框架传递复合对象报类型不匹配问题的解决方案

项目中使用的Web Service框架是Rop,在本次开发中,遇到了A对象的成员属性包含B对象,调用服务端时报B对象类型与传递的对象不匹配的问题。本人对Rop框架理解并不深,只是简单会用,好在网上关于Rop的资料不多,逐一筛下来,《rop入门(二)》这篇文章里,关于处理复合对象的内容对解决这个问题是很有针对性的,我在尝试该解决方案的过程中,做了一些调整,形成了一种变式方案,现摘取原方案并附我的调整,整理出来:

(注:我的解决方案在分割线后)

《rop入门(二)》文中,提到了两种解决方案:

1.手动将复合对象(UserInfo)转换成Json或xml格式

原文示例是手动拼接的....个人觉得还是使用一些现有的工具类,将实体转换成xml或json报文比较好。个人没有用这种方式。

2.配置自定义类型转换器

首先贴一个Rop示例中的TelephoneConverter,如下:

package com.rop.sample.request;
import com.rop.request.RopConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

public class TelephoneConverter implements RopConverter<String, Telephone> {
    @Override
    public Telephone convert(String source) {
        if (StringUtils.hasText(source)) {
            String zoneCode = source.substring(0, source.indexOf("-"));
            String telephoneCode = source.substring(source.indexOf("-") + 1);
            Telephone telephone = new Telephone();
            telephone.setZoneCode(zoneCode);
            telephone.setTelephoneCode(telephoneCode);
            return telephone;
        } else {
            return null;
        }
    }

    @Override
    public String unconvert(Telephone target) {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getZoneCode());
        sb.append("-");
        sb.append(target.getTelephoneCode());
        return null;
    }

    @Override
    public Class<String> getSourceClass() {
        return String.class;
    }

    @Override
    public Class<Telephone> getTargetClass() {
        return Telephone.class;
    }
}

转换器TelephoneConverter的逻辑很清晰,convert方法将指定格式的String解析为Telephone对象,unconvert反之。

转换器TelephoneConverter的配置如下:

<rop:annotation-driven formatting-conversion-service="conversionService"/>
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <!-- 将 xxxx-yyy 格式化串转换为 Telephone 对象 -->
            <bean class="com.rop.sample.request.TelephoneConverter"/>
        </set>
    </property>
</bean>

搜索rop的配置文件,找到 conversionService 的位置,TelephoneConverter是作为示例配置在此处的,新写自定义转换器时,添加该转换器的bean标签即可。

以上介绍了原文中转换器的写法和配置,下面简要介绍使用,我将简述rop请求的大致流程以便理解,以get方式请求为例:

DefaultRopClient ropClient;

//略去ropClient的初始化过程


//添加自定义转换器
ropClient.addRopConvertor(new TelephoneConverter());

//略去入参封装

//调用get方法进行rop调用
ropClient.buildClientRequest().get(ropRequest,ropResponseClass,methodName,version);

跟踪源码,只摘录与get请求流程有关的方法,顺次排列如下:

public <T> CompositeResponse get(RopRequest ropRequest, Class<T> ropResponseClass, String methodName, String version) {
            Map<String, String> requestParams = getRequestForm(ropRequest, methodName, version);
            return get(ropResponseClass, requestParams);
}


private Map<String, String> getRequestForm(RopRequest ropRequest, String methodName, String version) {

            Map<String, String> form = new LinkedHashMap<String, String>(16);

            //系统级参数
            form.put(SystemParameterNames.getAppKey(), appKey);
            form.put(SystemParameterNames.getMethod(), methodName);
            form.put(SystemParameterNames.getVersion(), version);
            form.put(SystemParameterNames.getFormat(), messageFormat.name());
            form.put(SystemParameterNames.getLocale(), locale.toString());
            if (sessionId != null) {
                form.put(SystemParameterNames.getSessionId(), sessionId);
            }

            //业务级参数
            form.putAll(getParamFields(ropRequest, messageFormat));

            //对请求进行签名
            String signValue = sign(ropRequest.getClass(), appSecret, form);
            form.put("sign", signValue);
            return form;
}

         /**
         * 获取ropRequest对应的参数名列表
         *
         * @param ropRequest
         * @param mf
         * @return
         */
        private Map<String, String> getParamFields(RopRequest ropRequest, MessageFormat mf) {
            if (!requestAllFields.containsKey(ropRequest.getClass())) {
                parseRopRequestClass(ropRequest);
            }
            return toParamValueMap(ropRequest, mf);
        }

         /**
         * 获取ropRequest对象的对应的参数列表
         *
         * @param ropRequest
         * @param mf
         * @return
         */
        private Map<String, String> toParamValueMap(RopRequest ropRequest, MessageFormat mf) {
            List<Field> fields = requestAllFields.get(ropRequest.getClass());
            Map<String, String> params = new HashMap<String, String>();
            for (Field field : fields) {
                RopConverter convertor = getConvertor(field.getType());
                Object fieldValue = ReflectionUtils.getField(field, ropRequest);
                if (fieldValue != null) {
                    if (convertor != null) {//有对应转换器
                        String strParamValue = (String) convertor.unconvert(fieldValue);
                        params.put(field.getName(), strParamValue);
                    } else if (field.getType().isAnnotationPresent(XmlRootElement.class) ||
                            field.getType().isAnnotationPresent(XmlType.class)) {
                        String message = MessageMarshallerUtils.getMessage(fieldValue, mf);
                        params.put(field.getName(), message);
                    } else {
                        params.put(field.getName(), fieldValue.toString());
                    }
                }
            }
            return params;
        }

toParamValueMap是一个关键方法。整体思想是将传入的实体转换成Map。如Convertor类完成了正确配置,并在ropClient调用rop请求前添加了转换器(ropClient.addRopConvertor(new TelephoneConverter());),那么在转换复合对象时,将调用该转换器的unconvert方法,将实体转换成自定义格式的字符串,之后put入map中,完成参数封装。

之后,开始正式执行get请求,此处就不再是rop的部分了,用了SpringFramework的RestTemplate类对象,调用getForObject(...)方法发起get请求:

private <T> CompositeResponse get(Class<T> ropResponseClass, Map<String, String> requestParams) {
            String responseContent = restTemplate.getForObject(buildGetUrl(requestParams), String.class, requestParams);
            if (logger.isDebugEnabled()) {
                logger.debug("response:\n" + responseContent);
            }
            return toCompositeResponse(responseContent, ropResponseClass);
}

在这个过程中,调用了TelephoneConverter的convert方法,将指定格式的字符串还原成Telephone对象。

之后,执行服务器端方法逻辑,完成后返回。返回时,不再调用TelephoneConverter,具体逻辑是:

根据rop配置文件中设置的数据格式(Json/xml),responseContent 为该格式的字符串。

String responseContent = restTemplate.getForObject(buildGetUrl(requestParams), String.class, requestParams);

将该字符串解析为真实实体类型并完成返回。 

 return toCompositeResponse(responseContent, ropResponseClass);
 private <T> CompositeResponse toCompositeResponse(String content, Class<T> ropResponseClass) {
            if(logger.isDebugEnabled()){
                logger.debug(content);
            }
            boolean successful = isSuccessful(content);
            DefaultCompositeResponse<T> compositeResponse = new DefaultCompositeResponse<T>(successful);

            if (MessageFormat.json == messageFormat) {
                if (successful) {
                    T ropResponse = jsonUnmarshaller.unmarshaller(content, ropResponseClass);
                    compositeResponse.setSuccessRopResponse(ropResponse);
                } else {
                    ErrorResponse errorResponse = jsonUnmarshaller.unmarshaller(content, ErrorResponse.class);
                    compositeResponse.setErrorResponse(errorResponse);
                }
            } else {
                if (successful) {
                    T ropResponse = xmlUnmarshaller.unmarshaller(content, ropResponseClass);
                    compositeResponse.setSuccessRopResponse(ropResponse);
                } else {
                    ErrorResponse errorResponse = xmlUnmarshaller.unmarshaller(content, ErrorResponse.class);
                    compositeResponse.setErrorResponse(errorResponse);
                }
            }
            return compositeResponse;
        }

以上就是原例的完整请求响应流程。

---------------------------------------------------------------------------------------------------------------------------

在我的实践中,由于不熟悉,并没有添加自定义转换器

//添加自定义转换器
ropClient.addRopConvertor(new TelephoneConverter());

由于这个疏忽,再加上一个习惯性小动作,反倒实现了我自己的解决方案,下面以User和UserInfo为例,阐述我的方案:

public class User extends AbstractRopRequest {

    private String userName;

    private UserInfo UserInfo;

    //省略getter、setter
    //省略toString()
}
public class UserInfo {

    private String birthday;
    
    private String telephone;

    private String address;

	@Override
	public String toString() {
		return "UserInfo [" + (birthday != null ? "birthday=" + birthday + ", " : "")
				+ (telephone != null ? "telephone=" + telephone + ", " : "")
				+ (address != null ? "address=" + address : "") + "]";
	}

    //省略getter、setter
}

如不对UserInfo类的对象做处理,在使用Rop传递User对象时,会报UserInfo类型和UserInfo对象不匹配。

我首先编写了UserInfoConvertor的编写及配置,但由于我没有 调用addRopConvertor()方法,所以在

 /**
         * 获取ropRequest对象的对应的参数列表
         *
         * @param ropRequest
         * @param mf
         * @return
         */
        private Map<String, String> toParamValueMap(RopRequest ropRequest, MessageFormat mf) {
            List<Field> fields = requestAllFields.get(ropRequest.getClass());
            Map<String, String> params = new HashMap<String, String>();
            for (Field field : fields) {
                RopConverter convertor = getConvertor(field.getType());
                Object fieldValue = ReflectionUtils.getField(field, ropRequest);
                if (fieldValue != null) {
                    if (convertor != null) {//有对应转换器
                        String strParamValue = (String) convertor.unconvert(fieldValue);
                        params.put(field.getName(), strParamValue);
                    } else if (field.getType().isAnnotationPresent(XmlRootElement.class) ||
                            field.getType().isAnnotationPresent(XmlType.class)) {
                        String message = MessageMarshallerUtils.getMessage(fieldValue, mf);
                        params.put(field.getName(), message);
                    } else {
                        params.put(field.getName(), fieldValue.toString());
                    }
                }
            }
            return params;
        }

toParamValueMap()方法执行时,没有获得到相应的 UserInfoConvertor ,封装时,由于UserInfo类中顺手为之的toString()方法,UserInfo对象在形式上,如同 userName这个普通String成员一样,以字符串形式被封装进params这个map中。

这样下来,可以将toString()方法视为UserInfoConvertor中的unconvert()方法,完成了从实体到字符串的转换。

某种程度上,自动生成的toString()方法简化了Convertor的编写,即不用再将对象属性一一获取出来,按照一定规则完成封装,这种简化随着对象属性数量的增长而愈发明显。

至此,客户端将对象转换为字符串的动作完成。

之后,客户端发送get请求:

​
String responseContent = restTemplate.getForObject(buildGetUrl(requestParams), String.class, requestParams);

​

服务端接收到get请求后,获取到请求参数,调用UserInfoConvertor的convert()方法开始将字符串解析成UserInfo对象。

与TelephoneConverter不同,此处 convert() 解析的为 toString() 生成的模板化字符串,如:

UserInfo [birthday=生日, telephone=电话, address=地址]

那么,掐头去尾,将中间的“属性名=属性值”的形式转存为map,再封装为UserInfo即可。我使用了自写工具类完成map到Object的封装。该工具类在  Farewell To Getter/Setter----参数封装工具类  一文中。

 @Override
 public UserInfo convert(String rowInfo) {
	 if (StringUtils.hasText(rowInfo)) {
	 //传入的字符串样例    UserInfo [birthday=生日, telephone=电话, address=地址]
	    String infoString = rowInfo.substring(rowInfo.indexOf("[")+1, rowInfo.indexOf("]"));   //掐头去尾
	    String[] infoArray = infoString.split(",");
	    HashMap<String, String> infoMap = new HashMap<String,String>();
	    for (String info : infoArray) {
	        String[] property = info.split("=");
	        infoMap.put(property[0].trim(), property[1].trim());
	    }
	    UserInfo info = new UserInfo();
	    try {  //调用自写工具类完成map到Object的自动化封装
	        SetPropertiesTool.map2Object(infoMap,SetPropertiesTool.LOWER_FIRST,info);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return info;
	 } else {
	    return null;
	 }
 }

一眼看去,似乎比原例中的方法复杂:

    @Override
    public Telephone convert(String source) {
        if (StringUtils.hasText(source)) {
            String zoneCode = source.substring(0, source.indexOf("-"));
            String telephoneCode = source.substring(source.indexOf("-") + 1);
            Telephone telephone = new Telephone();
            telephone.setZoneCode(zoneCode);
            telephone.setTelephoneCode(telephoneCode);
            return telephone;
        } else {
            return null;
        }
    }

但实际上,我的写法除了创建该类对象一句需要随新类更改:

 UserInfo info = new UserInfo();

其上下两部分均无需更改。

-------------------------------------------------------------------------------------------------------------------------------

综上,我的实现方式为:

1.新建复合对象(UserInfo)的Converter,并配置在rop.xml中

2.为复合对象自动生成toString()方法

3.Converter中unconvert()方法为空实现,只根据toString()方法的格式,编写convert()方法解析为实体。

完整UserInfoConverter示例如下:

public class UserInfoConverter implements RopConverter<String,UserInfo>{
    @Override
    public String unconvert(UserInfo info){
        return null;
    }

    @Override
     public UserInfo convert(String rowInfo) {
	     if (StringUtils.hasText(rowInfo)) {
	     //传入的字符串样例    UserInfo [birthday=生日, telephone=电话, address=地址]
	        String infoString = rowInfo.substring(rowInfo.indexOf("[")+1, rowInfo.indexOf("]"));   //掐头去尾
	        String[] infoArray = infoString.split(",");
	        HashMap<String, String> infoMap = new HashMap<String,String>();
	        for (String info : infoArray) {
	            String[] property = info.split("=");
	            infoMap.put(property[0].trim(), property[1].trim());
	        }
	        UserInfo info = new UserInfo();
	        try {  //调用自写工具类完成map到Object的自动化封装
	            SetPropertiesTool.map2Object(infoMap,SetPropertiesTool.LOWER_FIRST,info);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return info;
	     } else {
	        return null;
	     }
     }
    

    @Override
    public Class<String> getSourceClass(){
        return String.class;
    }
    
    @Override
    public Class<UserInfo> getTargetClass(){
        return UserInfo.class;
    }

}

 

以上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值