JABX生成与解析XML工具类

package com.wisetv.spark.dataautocontroller.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;


/**
 * 使用Jaxb2.0实现XML<->Java Object的Mapper.
 * 在创建时需要设定所有需要序列化的Root对象的Class.
 * 特别支持Root对象是Collection的情形.
 */
public class JaxbUtil {
    private static ConcurrentMap jaxbContexts = new ConcurrentHashMap();

    /**
     * Java Object->Xml without encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root) throws JAXBException {
        Class clazz = getUserClass(root);
        return toXml(root, clazz, null);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, String encoding) throws JAXBException {
        Class clazz = getUserClass(root);
        return toXml(root, clazz, encoding);
    }

    public static Class getUserClass(Object root){
        return root.getClass();
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, Class clazz, String encoding) throws JAXBException {

        StringWriter writer = new StringWriter();
        createMarshaller(clazz, encoding).marshal(root, writer);
        return writer.toString();

    }

    /**
     * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection root, String rootName, Class clazz) throws JAXBException {
        return toXml(root, rootName, clazz, null);
    }

    /**
     * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection root, String rootName, Class clazz, String encoding) throws JAXBException {

        CollectionWrapper wrapper = new CollectionWrapper();
        wrapper.collection = root;

        JAXBElement wrapperElement = new JAXBElement(new QName(rootName),
                CollectionWrapper.class, wrapper);

        StringWriter writer = new StringWriter();
        createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

        return writer.toString();

    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public static  T fromXml(String xml, Class clazz) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建Marshaller并设定encoding(可为null).
     * 线程不安全,需要每次创建或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Marshaller createMarshaller(Class clazz, String encoding) throws JAXBException {

        JAXBContext jaxbContext = getJaxbContext(clazz);

        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (StringUtils.isNotBlank(encoding)) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        }
        return marshaller;

    }

    /**
     * 创建UnMarshaller.
     * 线程不安全,需要每次创建或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Unmarshaller createUnmarshaller(Class clazz) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            e.printStackTrace();
        }

        return null;
    }

    @SuppressWarnings("rawtypes")
    protected static JAXBContext getJaxbContext(Class clazz) {
        Validate.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
                throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
                        + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

    /**
     * 封装Root Element 是 Collection的情况.
     */
    public static class CollectionWrapper {

        @XmlAnyElement
        protected Collection collection;
    }

    public static void main(String[] args) {
        Object a = (Object)new String();
        Class aClass = a.getClass();
        System.out.println(aClass.getName());
    }
}

演示

package com.wisetv.spark.test;

import com.wisetv.spark.dataautocontroller.bean.DataAutoAnalysisBean;
import com.wisetv.spark.dataautocontroller.bean.FieldsBean;
import com.wisetv.spark.dataautocontroller.bean.ProcessDataBean;
import com.wisetv.spark.dataautocontroller.bean.RecordBean;
import com.wisetv.spark.dataautocontroller.util.JaxbUtil;

import javax.xml.bind.JAXBException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataJobGenerate {

    public static void main(String[] args) {
        DataAutoAnalysisBean bean = new DataAutoAnalysisBean();
        bean.setFieldParser("iptv_parser");
        ProcessDataBean processDataBean = new ProcessDataBean();
        List fieldsBeanList = new ArrayList<>();
        FieldsBean fieldsBean1 = new FieldsBean();
        fieldsBean1.setFieldname("userid");
        fieldsBean1.setValue("userid");
        fieldsBeanList.add(fieldsBean1);
        FieldsBean fieldsBean2 = new FieldsBean();
        fieldsBean2.setFieldname("channelid");
        fieldsBean2.setValue("channelid");
        fieldsBeanList.add(fieldsBean2);
        FieldsBean fieldsBean3 = new FieldsBean();
        fieldsBean3.setFieldname("starttime");
        fieldsBean3.setValue("DateFromat('pre_time','yyyyMMddHHmmss','yyyyMMddHHmmss')");
        fieldsBeanList.add(fieldsBean3);
        FieldsBean fieldsBean4 = new FieldsBean();
        fieldsBean4.setFieldname("endtime");
        fieldsBean4.setValue("DateFromat('cur_time','yyyyMMddHHmmss','yyyyMMddHHmmss')");
        fieldsBeanList.add(fieldsBean4);
        processDataBean.setFieldList(fieldsBeanList);
        processDataBean.setType("3");
        processDataBean.setOutputPath("E:\\model\\aaa");
        processDataBean.setAbstractDisFunctionName("DefaultDisPatch");
        processDataBean.setDataDispatchProcessName("DataDispatchProcess");

        List processDataBeanList = new ArrayList<>();
        processDataBeanList.add(processDataBean);
        bean.setProcessDataList(processDataBeanList);


        List recordBeanList = new ArrayList<>();
        RecordBean recordBean1 = new RecordBean();
        recordBean1.setProcessName("LogPreProcessMax");
        recordBean1.setInputfile("e:/MapInfo.2019-04-20.log");
        recordBean1.setKeys("userid,stbtype");
        recordBean1.setResultName("LogPreProcessMax");
        recordBeanList.add(recordBean1);

        RecordBean recordBean2 = new RecordBean();
        recordBean2.setProcessName("LogPreProcessMin");
        recordBean2.setInputfile("e:/MapInfo.2019-04-20.log");
        recordBean2.setKeys("userid,stbtype");
        recordBean2.setResultName("LogPreProcessMin");
        recordBeanList.add(recordBean2);

        RecordBean recordBean3 = new RecordBean();
        recordBean3.setProcessName("LogPreProcessGroup");
        recordBean3.setInputfile("e:/MapInfo.2019-04-20.log");
        recordBean3.setKeys("userid,stbtype");
        recordBean3.setResultName("LogPreProcessGroup");
        List inputList = new ArrayList<>();
        inputList.add("LogPreProcessMax");
        inputList.add("LogPreProcessMin");
        recordBean3.setInputList(inputList);
        recordBeanList.add(recordBean3);
        inputList.clear();

        RecordBean recordBean4 = new RecordBean();
        recordBean4.setProcessName("LogPreProcessSort");
        recordBean4.setKeys("userid,stbtype");
        recordBean4.setResultName("LogPreProcessSort");

        inputList.add("LogPreProcessGroup");
        recordBeanList.add(recordBean4);
        inputList.clear();

        RecordBean recordBean5 = new RecordBean();
        recordBean5.setProcessName("LogPreProcessETL");
        recordBean5.setFunctionName("FilterChannelstatus");
        recordBean5.setAbstractFunctionType("AbstractETLFunction");
        recordBean5.setResultName("LogPreProcessETL");
        inputList.add("LogPreProcessSort");
        recordBeanList.add(recordBean5);

        RecordBean recordBean6 = new RecordBean();
        recordBean6.setProcessName("LogDataFormatProcess");
        recordBean6.setFunctionName("DefaultFormat");
        recordBean6.setAbstractFunctionType("AbstractFormatFunction");
        recordBean6.setResultName("LogDataFormatProcess");
        inputList.add("LogPreProcessSort");
        recordBeanList.add(recordBean6);


        bean.setRecordBeanList(recordBeanList);



        String xml = "\n" +
                "\n" +
                "    \n" +
                "        \n" +
                "            userid\n" +
                "            userid\n" +
                "        \n" +
                "        \n" +
                "            channelid\n" +
                "            channelid\n" +
                "        \n" +
                "        \n" +
                "            starttime\n" +
                "            DateFromat('pre_time','yyyyMMddHHmmss','yyyyMMddHHmmss')\n" +
                "        \n" +
                "        \n" +
                "            endtime\n" +
                "            DateFromat('cur_time','yyyyMMddHHmmss','yyyyMMddHHmmss')\n" +
                "        \n" +
                "        3\n" +
                "        E:\\model\\aaa\n" +
                "        DataDispatchProcess\n" +
                "        DefaultDisPatch\n" +
                "    \n" +
                "    \n" +
                "        LogPreProcessMax\n" +
                "        userid,stbtype\n" +
                "        e:/MapInfo.2019-04-20.log\n" +
                "        LogPreProcessMax\n" +
                "    \n" +
                "    \n" +
                "        LogPreProcessMin\n" +
                "        userid,stbtype\n" +
                "        e:/MapInfo.2019-04-20.log\n" +
                "        LogPreProcessMin\n" +
                "    \n" +
                "    \n" +
                "        LogPreProcessGroup\n" +
                "        userid,stbtype\n" +
                "        e:/MapInfo.2019-04-20.log\n" +
                "        LogPreProcessSort\n" +
                "        LogPreProcessSort\n" +
                "        LogPreProcessGroup\n" +
                "    \n" +
                "    \n" +
                "        LogPreProcessSort\n" +
                "        userid,stbtype\n" +
                "        LogPreProcessSort\n" +
                "    \n" +
                "    \n" +
                "        LogPreProcessETL\n" +
                "        FilterChannelstatus\n" +
                "        AbstractETLFunction\n" +
                "        LogPreProcessETL\n" +
                "    \n" +
                "    \n" +
                "        LogDataFormatProcess\n" +
                "        DefaultFormat\n" +
                "        AbstractFormatFunction\n" +
                "        LogDataFormatProcess\n" +
                "    \n" +
                "";

        DataAutoAnalysisBean bean1 = JaxbUtil.fromXml(xml, DataAutoAnalysisBean.class);
        System.out.println(bean1);
//        try {
//            System.out.println(JaxbUtil.toXml(bean));
//        } catch (JAXBException e) {
//            e.printStackTrace();
//        }
    }
}

你可能感兴趣的:(JAVA)