001/**
002 *
003 * Copyright 2017-2018 Florian Schmaus.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.util;
018
019import java.io.StringReader;
020import java.io.StringWriter;
021import java.util.logging.Level;
022import java.util.logging.Logger;
023
024import javax.xml.transform.OutputKeys;
025import javax.xml.transform.Transformer;
026import javax.xml.transform.TransformerException;
027import javax.xml.transform.TransformerFactory;
028import javax.xml.transform.stream.StreamResult;
029import javax.xml.transform.stream.StreamSource;
030
031public class XmlUtil {
032
033    private static final Logger LOGGER = Logger.getLogger(XmlUtil.class.getName());
034
035    private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();
036
037    static {
038        transformerFactory.setAttribute("indent-number", 2);
039    }
040
041    public static String prettyFormatXml(CharSequence xml) {
042        String xmlString = xml.toString();
043        StreamSource source = new StreamSource(new StringReader(xmlString));
044        StringWriter stringWriter = new StringWriter();
045        StreamResult result = new StreamResult(stringWriter);
046
047        try {
048            Transformer transformer = transformerFactory.newTransformer();
049            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
050            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
051            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
052
053            // Transform the requested string into a nice formatted XML string
054            transformer.transform(source, result);
055        }
056        catch (TransformerException | IllegalArgumentException e) {
057            LOGGER.log(Level.SEVERE, "Transformer error", e);
058            return xmlString;
059        }
060
061        return stringWriter.toString();
062    }
063}