package eu.dnetlib.is.util;

import java.io.StringWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import eu.dnetlib.is.resources.SimpleResourceService;

public class XmlIndenter {

	private static final Log log = LogFactory.getLog(SimpleResourceService.class);

	public static String indent(final String xml) {
		try {
			final Document doc = DocumentHelper.parseText(xml);
			return indent(doc);
		} catch (final Exception e) {
			log.warn("Error indenting xml");
			return xml;
		}
	}

	public static String indent(final Node node) {
		try {
			final StringWriter sw = new StringWriter();
			final XMLWriter writer = new XMLWriter(sw, OutputFormat.createPrettyPrint());
			writer.write(node);
			writer.close();
			return sw.toString();
		} catch (final Exception e) {
			log.warn("Error indenting xml");
			return node.asXML();
		}
	}

}
