JAXBContext中bean和xml之间的转换,以及xml相关的方法

 

JAXB是什么?

        JAXB(即Java Architecturefor XML Binding)是一个业界的标准,

        即是一项可以根据XML Schema产生Java类的技术。

        该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,

 

        并能将Java对象树的内容重新写到XML实例文档。

 

 

@Data@AllArgsConstructor@NoArgsConstructor //需要无惨构造器@XmlRootElementpublic class ClassA {     private String file1;    private String file2; }

 

测试类

public class jbTest {    public static void main(String[] args) {        // bean转换成xml        ClassA a=new ClassA("hello string","hello int");        System.out.println(a);        try {            JAXBContext context = JAXBContext.newInstance(ClassA.class);            Marshaller marshaller = context.createMarshaller();            marshaller.marshal(a,System.out);

        } catch (JAXBException e) {

            e.printStackTrace();S        }         printLine();         // xml转换成bean        String xmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +                "<classA><file1>hello string</file1><file2>hello int</file2></classA>";        try {            JAXBContext context = JAXBContext.newInstance(ClassA.class);

            Unmarshaller unmarshaller = context.createUnmarshaller();

            ClassA a2 = (ClassA) unmarshaller.unmarshal(new StringReader(xmlStr));            System.out.println(a2);        } catch (JAXBException e) {            e.printStackTrace();        }     }    public static void printLine(){        System.out.println("===============================");    }}

 

 

XStream使用(序列号xml)
导入pom文件        <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->        <dependency>            <groupId>com.thoughtworks.xstream</groupId>            <artifactId>xstream</artifactId>            <version>1.4.11.1</version>        </dependency>

测试代码

        XStream stream=new XStream();        stream.alias("hellowolrd",String.class);        String str = stream.toXML("str");        System.out.println(str);    //     结果:    //    <hellowolrd>str</hellowolrd>

这是基本用法,然后可以根据自己的需求扩展

 

 

Document使用拼接xml格式的文件
导入pom文件        <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->        <dependency>            <groupId>dom4j</groupId>            <artifactId>dom4j</artifactId>            <version>1.6.1</version>        </dependency>

测试代码和结果:

        Document root= DocumentHelper.createDocument();        Element html = root.addElement("html");        html.addElement("body").addText("txt_body");        html.addElement("head").addText("txt_head");        System.out.println(root.asXML());//        结果//        <?xml version="1.0" encoding="UTF-8"?>//      <html><body>txt_body</body><head>txt_head</head></html>      项目工具类 package com.hsbc.tt.boi.batchservicecommon.util; import com.hsbc.tt.boi.batchservicecommon.bean.ProcessorPayload;import com.hsbc.tt.boi.batchservicecommon.dispatch.factory.BulkProcessorFactory;import com.hsbc.tt.boi.common.dto.RoutingPayload;import com.hsbc.tt.boi.common.enums.MessageType;import java.io.StringReader;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import javax.xml.bind.DataBindingException;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Unmarshaller;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory; public final class MessageUnmarshallerUtil {    private static final Logger log = LoggerFactory.getLogger(MessageUnmarshallerUtil.class);    private static final Map<MessageType, JAXBContext> JAXB_CONTEXT_MESSAGE_MAP = new ConcurrentHashMap();     private MessageUnmarshallerUtil() {    } private static Unmarshaller createUnmarshaller(String messageType) {// valueOf获取枚举参数,null抛出异常。        MessageType type = MessageType.valueOf(StringUtils.upperCase(messageType));         try {//创建Unmarshaller对象(xml转成been)。            return ((JAXBContext)JAXB_CONTEXT_MESSAGE_MAP.get(type)).createUnmarshaller();        } catch (JAXBException var3) {            throw new DataBindingException(var3);        }    }     public static ProcessorPayload unmarshaller(RoutingPayload routingPayload) {        try {            return new ProcessorPayload(routingPayload, createUnmarshaller(routingPayload.getMessageType()).unmarshal(new StringReader(routingPayload.getOriginalMsg())));        } catch (JAXBException var2) {            throw new DataBindingException(var2);        }    }     public static List<ProcessorPayload<?>> unmarshaller(final List<RoutingPayload> routingPayloads) {        try {            long startDate = System.currentTimeMillis();            Map<String, Unmarshaller> unmarshallerCache = new HashMap();            List<ProcessorPayload<?>> processorPayloads = new ArrayList(routingPayloads.size());            Iterator var5 = routingPayloads.iterator();             while(var5.hasNext()) {                RoutingPayload routingPayload = (RoutingPayload)var5.next();                Unmarshaller unmarshaller = (Unmarshaller)unmarshallerCache.computeIfAbsent(routingPayload.getMessageType(), (e) -> {                    return createUnmarshaller(routingPayload.getMessageType());                });                processorPayloads.add(new ProcessorPayload(routingPayload, unmarshaller.unmarshal(new StringReader(routingPayload.getOriginalMsg()))));            }             log.info("Unmarshaller {} entities, cost {}", routingPayloads.size(), (System.currentTimeMillis() - startDate) / 1000L);            return processorPayloads;        } catch (JAXBException var8) {            throw new DataBindingException(var8);        }    }     static {        BulkProcessorFactory.HTS_MESSAGE_MAP.forEach((key, value) -> {            try {                JAXB_CONTEXT_MESSAGE_MAP.put(value, JAXBContext.newInstance(new Class[]{key}));            } catch (JAXBException var3) {                throw new DataBindingException(var3);            }        });    }}

 

 

 

package com.hsbc.tt.boi.batchservicecommon.bean;

 

import com.hsbc.tt.boi.batchservicecommon.entity.ProcessorLock;

import com.hsbc.tt.boi.common.dto.RoutingPayload;

import com.hsbc.tt.boi.common.htsmsgentity.accounting.AccountEntries;

import com.hsbc.tt.boi.common.htsmsgentity.accounting.Accounting;

import com.hsbc.tt.boi.common.htsmsgentity.accounting.Body;

import com.hsbc.tt.boi.common.htsmsgentity.balancemis.BalanceMis;

import com.hsbc.tt.boi.common.htsmsgentity.balancemis.SubHeader;

import com.hsbc.tt.boi.common.htsmsgentity.lmtchk.Lmtchk;

import java.util.Iterator;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

 

public class ProcessorPayload<E> {

    private final RoutingPayload routingPayload;

    private final E proponix;

    private String processor;

    private ProcessorPayload original;

    private ProcessorLock processorLock;

    private ProcessStatus result;

    private int resultCount;

    private StringBuilder resultDesc;

    private boolean requiredRollback;

 

    public ProcessorPayload(RoutingPayload routingPayload, E proponix) {

        this.result = ProcessStatus.PENDING;

        this.resultDesc = new StringBuilder();

        this.requiredRollback = false;

        this.routingPayload = routingPayload;

        this.proponix = proponix;

        this.rightPadFixLength(proponix);

    }

 

    private void rightPadFixLength(E proponix) {

        String limitCustomerID;

        String limitCustomerID;

        if (proponix instanceof BalanceMis) {

            BalanceMis balanceMis = (BalanceMis)proponix;

            if (null != balanceMis) {

                SubHeader subHeader = balanceMis.getSubHeader();

                if (null != subHeader) {

                    limitCustomerID = subHeader.getRelationshipCustomerID();

                    balanceMis.getSubHeader().setRelationshipCustomerID(this.rightPadEight(limitCustomerID));

                    limitCustomerID = subHeader.getLimitCustomerID();

                    balanceMis.getSubHeader().setLimitCustomerID(this.rightPadEight(limitCustomerID));

                }

            }

        }

 

        if (proponix instanceof Lmtchk) {

            Lmtchk lmtchk = (Lmtchk)proponix;

            if (null != lmtchk) {

                com.hsbc.tt.boi.common.htsmsgentity.lmtchk.SubHeader subHeader = lmtchk.getSubHeader();

                if (null != subHeader) {

                    limitCustomerID = subHeader.getLimitCustomerID();

                    lmtchk.getSubHeader().setLimitCustomerID(this.rightPadEight(limitCustomerID));

                }

            }

        }

 

        if (proponix instanceof Accounting) {

            Accounting accounting = (Accounting)proponix;

            if (null != accounting) {

                com.hsbc.tt.boi.common.htsmsgentity.accounting.SubHeader subHeader = accounting.getSubHeader();

                if (null != subHeader) {

                    limitCustomerID = subHeader.getLimitCustomerID();

                    accounting.getSubHeader().setLimitCustomerID(this.rightPadEight(limitCustomerID));

                    String relationshipCustomerID = subHeader.getRelationshipCustomerID();

                    accounting.getSubHeader().setRelationshipCustomerID(this.rightPadEight(relationshipCustomerID));

                }

 

                Body body = accounting.getBody();

                if (null != body) {

                    List<AccountEntries> accountEntriesList = body.getAccountEntries();

                    Iterator var14 = accountEntriesList.iterator();

 

                    while(var14.hasNext()) {

                        AccountEntries accountEntries = (AccountEntries)var14.next();

                        accountEntries.setSettlementCustomerID(this.rightPadEight(accountEntries.getSettlementCustomerID()));

                    }

                }

            }

        }

 

    }

 

    private ProcessorPayload(ProcessorPayload<E> original, String processor) {

        this.result = ProcessStatus.PENDING;

        this.resultDesc = new StringBuilder();

        this.requiredRollback = false;

        this.processor = processor;

        this.routingPayload = original.routingPayload;

        this.proponix = original.proponix;

        this.original = original;

        this.resultDesc = new StringBuilder(processor);

        this.result = ProcessStatus.PENDING;

    }

 

    private String rightPadEight(String val) {

        if (StringUtils.isEmpty(val)) {

            val = "";

        }

 

        return StringUtils.rightPad(val, 18, '8');

    }

 

    public ProcessorPayload<E> cloneNew(String processor) {

        return new ProcessorPayload(this, processor);

    }

 

    public void setResult(final ProcessStatus result) {

        this.result = result;

    }

 

    public void setResult(final ProcessStatus result, final CharSequence errorMsg) {

        this.setResult(result);

        this.setResultDesc(errorMsg);

    }

 

    public void setResultDesc(final CharSequence errorMsg) {

        if (errorMsg != null) {

            this.resultDesc.append(" ").append(++this.resultCount).append(".").append(errorMsg);

        }

 

    }

 

    public boolean isProcessable() {

        return ProcessStatus.PENDING.equals(this.result);

    }

 

    public boolean isProcessorAlreadyCompleted() {

        return this.processorLock == null && ProcessStatus.COMPLETE.equals(this.result);

    }

 

    public boolean isComplete() {

        return ProcessStatus.COMPLETE.equals(this.result);

    }

 

    public void resetStatus() {

        this.result = ProcessStatus.PENDING;

        this.setResultDesc("reset");

        this.processorLock = null;

        this.requiredRollback = false;

    }

 

    public synchronized void mergeResult(ProcessorPayload processorPayload) {

        ProcessStatus status = processorPayload.getResult();

        if (!ProcessStatus.ERROR.equals(this.result) && !ProcessStatus.NOT_READY.equals(this.result)) {

            this.setResult(status, processorPayload.getResultDesc());

        }

 

    }

 

    public RoutingPayload getRoutingPayload() {

        return this.routingPayload;

    }

 

    public E getProponix() {

        return this.proponix;

    }

 

    public String getProcessor() {

        return this.processor;

    }

 

    public ProcessorPayload getOriginal() {

        return this.original;

    }

 

    public ProcessorLock getProcessorLock() {

        return this.processorLock;

    }

 

    public ProcessStatus getResult() {

        return this.result;

    }

 

    public int getResultCount() {

        return this.resultCount;

    }

 

    public StringBuilder getResultDesc() {

        return this.resultDesc;

    }

 

    public boolean isRequiredRollback() {

        return this.requiredRollback;

    }

 

    public void setProcessor(final String processor) {

        this.processor = processor;

    }

 

    public void setOriginal(final ProcessorPayload original) {

        this.original = original;

    }

 

    public void setProcessorLock(final ProcessorLock processorLock) {

        this.processorLock = processorLock;

    }

 

    public void setResultCount(final int resultCount) {

        this.resultCount = resultCount;

    }

 

    public void setRequiredRollback(final boolean requiredRollback) {

        this.requiredRollback = requiredRollback;

    }

 

    public boolean equals(final Object o) {

        if (o == this) {

            return true;

        } else if (!(o instanceof ProcessorPayload)) {

            return false;

        } else {

            ProcessorPayload<?> other = (ProcessorPayload)o;

            if (!other.canEqual(this)) {

                return false;

            } else {

                label103: {

                    Object this$routingPayload = this.getRoutingPayload();

                    Object other$routingPayload = other.getRoutingPayload();

                    if (this$routingPayload == null) {

                        if (other$routingPayload == null) {

                            break label103;

                        }

                    } else if (this$routingPayload.equals(other$routingPayload)) {

                        break label103;

                    }

 

                    return false;

                }

 

                Object this$proponix = this.getProponix();

                Object other$proponix = other.getProponix();

                if (this$proponix == null) {

                    if (other$proponix != null) {

                        return false;

                    }

                } else if (!this$proponix.equals(other$proponix)) {

                    return false;

                }

 

                label89: {

                    Object this$processor = this.getProcessor();

                    Object other$processor = other.getProcessor();

                    if (this$processor == null) {

                        if (other$processor == null) {

                            break label89;

                        }

                    } else if (this$processor.equals(other$processor)) {

                        break label89;

                    }

 

                    return false;

                }

 

                Object this$original = this.getOriginal();

                Object other$original = other.getOriginal();

                if (this$original == null) {

                    if (other$original != null) {

                        return false;

                    }

                } else if (!this$original.equals(other$original)) {

                    return false;

                }

 

                label75: {

                    Object this$processorLock = this.getProcessorLock();

                    Object other$processorLock = other.getProcessorLock();

                    if (this$processorLock == null) {

                        if (other$processorLock == null) {

                            break label75;

                        }

                    } else if (this$processorLock.equals(other$processorLock)) {

                        break label75;

                    }

 

                    return false;

                }

 

                Object this$result = this.getResult();

                Object other$result = other.getResult();

                if (this$result == null) {

                    if (other$result != null) {

                        return false;

                    }

                } else if (!this$result.equals(other$result)) {

                    return false;

                }

 

                if (this.getResultCount() != other.getResultCount()) {

                    return false;

                } else {

                    label60: {

                        Object this$resultDesc = this.getResultDesc();

                        Object other$resultDesc = other.getResultDesc();

                        if (this$resultDesc == null) {

                            if (other$resultDesc == null) {

                                break label60;

                            }

                        } else if (this$resultDesc.equals(other$resultDesc)) {

                            break label60;

                        }

 

                        return false;

                    }

 

                    if (this.isRequiredRollback() != other.isRequiredRollback()) {

                        return false;

                    } else {

                        return true;

                    }

                }

            }

        }

    }

 

    protected boolean canEqual(final Object other) {

        return other instanceof ProcessorPayload;

    }

 

    public int hashCode() {

        int PRIME = true;

        int result = 1;

        Object $routingPayload = this.getRoutingPayload();

        int result = result * 59 + ($routingPayload == null ? 43 : $routingPayload.hashCode());

        Object $proponix = this.getProponix();

        result = result * 59 + ($proponix == null ? 43 : $proponix.hashCode());

        Object $processor = this.getProcessor();

        result = result * 59 + ($processor == null ? 43 : $processor.hashCode());

        Object $original = this.getOriginal();

        result = result * 59 + ($original == null ? 43 : $original.hashCode());

        Object $processorLock = this.getProcessorLock();

        result = result * 59 + ($processorLock == null ? 43 : $processorLock.hashCode());

        Object $result = this.getResult();

        result = result * 59 + ($result == null ? 43 : $result.hashCode());

        result = result * 59 + this.getResultCount();

        Object $resultDesc = this.getResultDesc();

        result = result * 59 + ($resultDesc == null ? 43 : $resultDesc.hashCode());

        result = result * 59 + (this.isRequiredRollback() ? 79 : 97);

        return result;

    }

 

    public String toString() {

        return "ProcessorPayload(routingPayload=" + this.getRoutingPayload() + ", proponix=" + this.getProponix() + ", processor=" + this.getProcessor() + ", original=" + this.getOriginal() + ", processorLock=" + this.getProcessorLock() + ", result=" + this.getResult() + ", resultCount=" + this.getResultCount() + ", resultDesc=" + this.getResultDesc() + ", requiredRollback=" + this.isRequiredRollback() + ")";

    }

}

 

 

 

 

 

 

 

package com.hsbc.tt.boi.common.htsmsgentity.balancemis;

 

import com.hsbc.tt.boi.common.dto.HtsMessage;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlType;

 

// 控制默认情况下是否对字段或 Javabean 属性进行系列化

//FIELD:    JAXB 绑定类中的每个非静态、非瞬态字段将会自动绑定到 XML,除非由 XmlTransient 注释。

@XmlAccessorType(XmlAccessType.FIELD)

//指定生成元素的顺序。propOrder的值为{"name", "addr", "area"},生成的xml元素必须按照propOrder指定的顺序排序。

@XmlType(

    name = "",s

    propOrder = {"header", "subHeader", "userHeader", "body"}

)

//将类或枚举类型映射到 XML 元素。JAXB中的注解,用来根据java类生成xml内容。

@XmlRootElement(

    name = "Proponix"

)

public class BalanceMis implements HtsMessage {

//将被注解的字段(非静态),或者被注解的get/set方法对应的字段映射为本地元素,也就是子元素

    @XmlElement(

        name = "Header",

        required = true

    )

    protected Header header;

    @XmlElement(

        name = "SubHeader",

        required = true

    )

    protected SubHeader subHeader;

    @XmlElement(

        name = "UserHeader"

    )

    protected UserHeader userHeader;

    @XmlElement(

        name = "Body",

        required = true

    )

    protected Body body;

 

    public BalanceMis() {

    }

 

    public Header getHeader() {

        return this.header;

    }

 

    public void setHeader(Header value) {

        this.header = value;

    }

 

    public SubHeader getSubHeader() {

        return this.subHeader;

    }

 

    public void setSubHeader(SubHeader value) {

        this.subHeader = value;

    }

 

    public UserHeader getUserHeader() {

        return this.userHeader;

    }

 

    public void setUserHeader(UserHeader value) {

        this.userHeader = value;

    }

 

    public Body getBody() {

        return this.body;

    }

 

    public void setBody(Body value) {

        this.body = value;

    }

}