package com.ym.mec.collectfee.utils;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.javabean.BeanProvider;
import com.thoughtworks.xstream.converters.javabean.JavaBeanConverter;
import com.ym.mec.collectfee.entity.RequestHead;

public final class XStreamUtil {

	private XStreamUtil() {

	}

	/**
	 * 将包含xml内容的流转换成对�?
	 * 
	 * @param rootNode
	 *            根节点名�?
	 * @param rootNodeType
	 *            根节点类�?
	 * @param inputStream
	 *            �?
	 * @return 返回转换后的对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xmlToObject(String rootNode, Class<T> rootNodeType,
			String body) {
		XStream xStream = new XStream();// 默认用xppDriver
		xStream.autodetectAnnotations(true);
		xStream.alias(rootNode, rootNodeType);// 尽可能的加上，否则会抛CannotResolveClassException异常
		// 将xml转换成对�?
		return (T) xStream.fromXML(body);
	}

	/**
	 * 将对象转换成xml
	 * 
	 * @param rootNodeName
	 *            根节点名�?
	 * @param obj
	 *            对象�?
	 * @return
	 */
	public static String objectToXml(String rootNodeName, Object obj) {
		XStream xStream = new XStream();
		xStream.registerConverter(new JavaBeanConverter(xStream.getMapper(),
				new BeanProvider()), XStream.PRIORITY_VERY_LOW);
		xStream.alias(rootNodeName, obj.getClass());
		return xStream.toXML(obj);
	}

	public static String encryption(String body) {
		String re_md5 = new String();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(body.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			re_md5 = buf.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return re_md5.toUpperCase();
	}

}
