/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.xml.w3c;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * @author 田平 create 2016年10月12日上午11:21:49
 */
public class DocBuilderUtil {
	protected static final Log log = LogFactory.getLog(DocBuilderUtil.class);
	private static ThreadLocal<DocumentBuilderFactory> factory = ThreadLocal.withInitial(() -> DocumentBuilderFactory.newInstance());
	private static ThreadLocal<DocumentBuilder> builder = new ThreadLocal<>();

	public static DocumentBuilder getDocBuilder() {
		if (builder.get() == null) {
			DocumentBuilder docB = null;
			try {
				docB = factory.get().newDocumentBuilder();
			} catch (ParserConfigurationException e) {
				throw new RuntimeException("DocBuilderUtil.getDocBuilder error!", e);
			}
			builder.set(docB);
			return docB;
		} else {
			return builder.get();
		}
	}

	public static Document buildDocument() {
		DocumentBuilder builder = getDocBuilder();
		return builder.newDocument();
	}

}
