解決Apache CXF 不支持傳遞java.sql.Timestamp和java.util.HashMap類型問題

      在項目中使用Apache開源的Services Framework CXF來發布WebService,CXF可以很簡潔與Spring Framework 集成在一塊兒,在發佈WebService的過程當中,發佈的接口的入參有些類型支持不是很好,好比Timestamp和Map。這個時候咱們就須要編寫一些適配來實行類型轉換。java

 

TimestampAdapter.javaweb

package com.loongtao.general.crawler.webservice.utils;

import java.sql.Timestamp;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * <java.sql.Timestamp類型轉換> <功能詳細描述>
 * 在相應的字段前面  加上  @XmlJavaTypeAdapter(TimestampAdapter.class)
 * @author Lilin
 */
public class TimestampAdapter extends XmlAdapter<String, Timestamp> {

    /**
     * <一句話功能簡述> <功能詳細描述>
     * 
     * @param time
     * @return
     * @throws Exception
     * @see [類、類#方法、類#成員]
     */
    public String marshal(Timestamp time) throws Exception {
        return DateUtil.timestamp2Str(time);
    }

    /**
     * <一句話功能簡述> <功能詳細描述>
     * 
     * @param v
     * @throws Exception
     * @see [類、類#方法、類#成員]
     */
    public Timestamp unmarshal(String str) throws Exception {
        return DateUtil.str2Timestamp(str);
    }
}

DateUtil.javasql

package com.loongtao.general.crawler.webservice.utils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

import org.apache.log4j.Logger;

/**
 * <一句話功能簡述> <功能詳細描述>
 * 
 * @author Lilin
 * @version
 * @see [相關類/方法]
 * @since [產品/模塊版本]
 */
public class DateUtil {
    /**
     * 註釋內容
     */
    private static final Logger log = Logger.getLogger(DateUtil.class);
    /**
     * 默認日期格式
     */
    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * <默認構造函數>
     */
    private DateUtil() {
    }

    /**
     * <字符串轉換成日期> <若是轉換格式爲空,則利用默認格式進行轉換操做>
     * 
     * @param str
     *            字符串
     * @param format
     *            日期格式
     * @return 日期
     * @see [類、類#方法、類#成員]
     */
    public static Date str2Date(String str, String format) {
        if (null == str || "".equals(str)) {
            return null;
        }
        // 若是沒有指定字符串轉換的格式,則用默認格式進行轉換
        if (null == format || "".equals(format)) {
            format = DEFAULT_FORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(str);
            return date;
        } catch (ParseException e) {
            log.error("Parse string to date error!String : " + str);
        }

        return null;
    }

    /**
     * <一句話功能簡述> <功能詳細描述>
     * 
     * @param date
     *            日期
     * @param format
     *            日期格式
     * @return 字符串
     * @see [類、類#方法、類#成員]
     */
    public static String date2Str(Date date, String format) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * <時間戳轉換爲字符串> <功能詳細描述>
     * 
     * @param time
     * @return
     * @see [類、類#方法、類#成員]
     */
    public static String timestamp2Str(Timestamp time) {
        Date date = new Date(time.getTime());
        return date2Str(date, DEFAULT_FORMAT);
    }

    /**
     * <一句話功能簡述> <功能詳細描述>
     * 
     * @param str
     * @return
     * @see [類、類#方法、類#成員]
     */
    public static Timestamp str2Timestamp(String str) {
        Date date = str2Date(str, DEFAULT_FORMAT);
        return new Timestamp(date.getTime());
    }
}

在具體的Java Bean 中,經過@XmlJavaTypeAdapter註解來通知CXF進行類型轉換,具體請看ErrInfo中的屬性timestamp的getter 和setterapache

/*   
 * Copyright (c) 2014-2024 . All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * LoongTao. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with LoongTao.   
 *   
 */
package com.loongtao.general.crawler.webservice.vo;

import java.io.Serializable;
import java.sql.Timestamp;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.loongtao.general.crawler.webservice.utils.TimestampAdapter;

/**
 * @declare: 下載失敗信息<br>
 * @author: cphmvp
 * @version: 1.0
 * @date: 2014年9月22日下午3:47:26
 */
public class ErrInfo implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -5298849636495962631L;
    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getArticleMediaId() {
        return articleMediaId;
    }

    public void setArticleMediaId(int articleMediaId) {
        this.articleMediaId = articleMediaId;
    }
    
    @XmlJavaTypeAdapter(TimestampAdapter.class)
    public Timestamp getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Timestamp timestamp) {
        this.timestamp = timestamp;
    }

    private String url;
    private int articleMediaId;
    private Timestamp timestamp;

}

這個時候CXF解析Java Bean ErrInfo的時候,解析到@XmlJavaTypeAdapter註解時候就會以TimestampAdapter這個適配器來進行Timestamp與String之間的轉換。ide

Map:

用xstream將Map轉換成String函數

package com.loongtao.general.crawler.webservice.utils;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.apache.cxf.aegis.type.java5.XmlType;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import javax.xml.bind.annotation.XmlAccessType;  
import javax.xml.bind.annotation.XmlAccessorType;  

/**
 * <數據模型轉換> <Map<String,Object> 與 String之間的轉換>
 * 
 * @author Lilin
 * @version
 * @see [相關類/方法]
 * @since [產品/模塊版本]
 */
@XmlType(name = "MapAdapter")
@XmlAccessorType(XmlAccessType.FIELD)
public class MapAdapter extends XmlAdapter<String, Map<String, Object>> {
    /**
     * Convert a bound type to a value type. 轉換JAXB不支持的對象類型爲JAXB支持的對象類型
     * 
     * @param map
     *            map The value to be convereted. Can be null.
     * @return String
     * @throws Exception
     *             if there's an error during the conversion. The caller is
     *             responsible for reporting the error to the user through
     *             {@link javax.xml.bind.ValidationEventHandler}.
     */
    public String marshal(Map<String, Object> map) throws Exception {
        XStream xs = new XStream(new DomDriver());
        return xs.toXML(map);
    }

    /**
     * Convert a value type to a bound type. 轉換JAXB支持的對象類型爲JAXB不支持的的類型
     * 
     * @param model
     *            The value to be converted. Can be null.
     * @return Map<String,Object>
     * @throws Exception
     *             if there's an error during the conversion. The caller is
     *             responsible for reporting the error to the user through
     *             {@link javax.xml.bind.ValidationEventHandler}.
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> unmarshal(String model) throws Exception {
        XStream xs = new XStream(new DomDriver());
        return (HashMap) xs.fromXML(model);
    }
}
相關文章
相關標籤/搜索