package com.zbkj.service.wangshang.api.internal.util;


import com.zbkj.service.wangshang.api.MybankApiException;
import com.zbkj.service.wangshang.api.MybankApiExceptionEnum;
import com.zbkj.service.wangshang.api.MybankConstants;
import com.zbkj.service.wangshang.api.domain.Request;
import com.zbkj.service.wangshang.api.domain.RequestBody;
import com.zbkj.service.wangshang.api.domain.RequestDocument;
import com.zbkj.service.wangshang.api.domain.RequestHead;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 * Encapsulating XML common operations
 */
public final class XmlUtils {

    public static String requestXmlBuild(RequestHead requestHead, RequestBody requestBody) throws MybankApiException {
        if (null == requestHead || null == requestBody) {
            throw new MybankApiException(MybankApiExceptionEnum.BUILD_XML_EXCEPTION);
        }
        return JaxbUtil.convertToXml(new RequestDocument(new Request(requestHead, requestBody)), MybankConstants.CHARSET_UTF8);
    }

    /**
     * XML报文格式检查
     *
     * @param xmlContent
     * @return true/false
     */
    public static boolean isXmlDocument(String xmlContent) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlContent)));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
