Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys INDENT.

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

From source file:com.meltmedia.rodimus.RodimusCli.java

public static void transformDocument(File inputFile, File outputDir, boolean verbose) throws Exception {
    StreamSource xhtmlHandlerSource = createStreamSource(RodimusCli.class.getResource("/rodimus.xsl"));

    File indexFile = new File(outputDir, "index.html");
    File assetDir = new File(outputDir, IMAGE_DIR_NAME);
    assetDir.mkdirs();/*w w w .  j a v a  2  s .  c  o  m*/

    // Set up the output buffer.
    StringBuilderWriter output = new StringBuilderWriter();

    // Set up the serializer.
    ToXMLStream serializer = new ToXMLStream();
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, String.valueOf(2));
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_ENTITIES, "yes");
    serializer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
    serializer.setWriter(output);

    // Set up the xhtmlStructure handler.
    TransformerHandler xhtmlHandler = getContentHandler(xhtmlHandlerSource);
    xhtmlHandler.setResult(new SAXResult(serializer));

    // build the Tika handler.
    ParseContext context = createParseContext(assetDir, verbose);
    PostTikaHandler cleanUp = new PostTikaHandler(IMAGE_DIR_NAME);
    cleanUp.setContentHandler(xhtmlHandler);
    parseInput(createInputStream(inputFile), cleanUp, context, verbose);

    // Do some regular expression cleanup.
    String preOutput = output.toString();
    preOutput = preOutput.replaceAll("/>", " />");
    // TODO: img is in this list, but it is not a block level element.
    String blockLevel = "(?:address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|noscript|ol|output|p|pre|sectop|table|tfoot|ul|video|img)";
    preOutput = preOutput.replaceAll("(</" + blockLevel + ">)(\\s*)(<" + blockLevel + ")", "$1$2$2$3");
    preOutput = "<!doctype html>\n" + preOutput;

    FileUtils.write(indexFile, preOutput, "UTF-8");

    // Clean out images dir if it's empty
    if (assetDir.list().length == 0) {
        FileUtils.deleteQuietly(assetDir);
    }
}

From source file:com.summer.logger.LoggerPrinter.java

  /**
 * Formats the json content and print it
 *
 * @param xml the xml content//from w w  w .  j a v a 2 s  .  c o  m
 */
@Override public void xml(String xml) {
  if (TextUtils.isEmpty(xml)) {
    d("Empty/Null xml content");
    return;
  }
  try {
    Source xmlInput = new StreamSource(new StringReader(xml));
    StreamResult xmlOutput = new StreamResult(new StringWriter());
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(xmlInput, xmlOutput);
    d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
  } catch (TransformerException e) {
    e(e.getCause().getMessage() + "\n" + xml);
  }
}

From source file:com.urbancode.x2o.xml.XmlWrite.java

public Transformer createTransformer() throws TransformerConfigurationException {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    return transformer;
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {//w w  w.j a va 2s.c  o m
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

From source file:com.mirth.connect.plugins.datatypes.dicom.DICOMSerializer.java

@Override
public String toXML(String source) throws MessageSerializerException {
    try {/*from ww  w .j av a 2  s . c  o  m*/
        byte[] encodedMessage = org.apache.commons.codec.binary.StringUtils.getBytesUsAscii(source);

        StringWriter output = new StringWriter();
        DicomInputStream dis = new DicomInputStream(
                new BufferedInputStream(new Base64InputStream(new ByteArrayInputStream(encodedMessage))));
        /*
         * This parameter was added in dcm4che 2.0.28. We use it to retain the memory allocation
         * behavior from 2.0.25.
         * http://www.mirthcorp.com/community/issues/browse/MIRTH-2166
         * http://www.dcm4che.org/jira/browse/DCM-554
         */
        dis.setAllocateLimit(-1);

        try {
            SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
            TransformerHandler handler = factory.newTransformerHandler();
            handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "no");
            handler.setResult(new StreamResult(output));

            final SAXWriter writer = new SAXWriter(handler, null);
            dis.setHandler(writer);
            dis.readDicomObject(new BasicDicomObject(), -1);
            String serializedDicomObject = output.toString();

            // rename the "attr" element to the tag ID
            Document document = documentSerializer.fromXML(serializedDicomObject);
            NodeList attrElements = document.getElementsByTagName("attr");

            for (int i = 0; i < attrElements.getLength(); i++) {
                Element attrElement = (Element) attrElements.item(i);
                renameAttrToTag(document, attrElement);
            }

            return documentSerializer.toXML(document);
        } catch (Exception e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(dis);
            IOUtils.closeQuietly(output);

            if (dis != null) {
                dis.close();
            }
        }
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting DICOM to XML", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting DICOM to XML", e));
    }
}

From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * Instantiates a new navigation manager.
 *///  w  ww.  jav  a  2 s  .co  m
private NavigationManager() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentTransformer = TransformerFactory.newInstance().newTransformer();
        documentTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    controller = getController();

    List<Class<?>> classes = new ArrayList<Class<?>>(ACTIONS.length);
    classes.addAll(Arrays.asList(ACTIONS));

    // InputStream actionsXmlStream =
    // NavigationManager.class.getResourceAsStream("/actions.xml");
    // if (actionsXmlStream != null) {
    // try {
    // Document actionsDocument = documentBuilder.parse(actionsXmlStream);
    // addActions(actionsDocument, classes);
    // } catch (Exception e) {
    // logger.error(e);
    // }
    // }

    actions = new TreeMap<String, Class<? extends AbstractAction>>();

    for (Class<?> classAction : classes) {
        try {
            AbstractAction abstractAction = (AbstractAction) classAction.newInstance();
            actions.put(abstractAction.getActionName(), abstractAction.getClass());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("Error while registering actions", e);
            }
        }
    }
}

From source file:tut.pori.javadocer.Javadocer.java

/**
 * /*w  w  w  . j av  a  2s .co m*/
 * @throws IllegalArgumentException
 */
public Javadocer() throws IllegalArgumentException {
    _restUri = System.getProperty(PROPERTY_REST_URI);
    if (StringUtils.isBlank(_restUri)) {
        throw new IllegalArgumentException("Bad " + PROPERTY_REST_URI);
    }

    try {
        _documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        _transformer = TransformerFactory.newInstance().newTransformer();
        _transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        _transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // because of an issue with java's transformer indent, we need to add standalone attribute 
        _transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        _transformer.setOutputProperty(OutputKeys.ENCODING, CHARSET);
        _transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        _transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    } catch (ParserConfigurationException | TransformerConfigurationException
            | TransformerFactoryConfigurationError ex) {
        LOGGER.error(ex, ex);
        throw new IllegalArgumentException("Failed to create document builder/transformer instance.");
    }

    _xPath = XPathFactory.newInstance().newXPath();
    _client = HttpClients.createDefault();
}

From source file:com.omertron.thetvdbapi.tools.DOMHelper.java

/**
 * Write the Document out to a file using nice formatting
 *
 * @param doc The document to save//from w  w  w .java2 s .  c o  m
 * @param localFile The file to write to
 * @return
 */
public static boolean writeDocumentToFile(Document doc, String localFile) {
    try {
        TransformerFactory transfact = TransformerFactory.newInstance();
        Transformer trans = transfact.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
        trans.setOutputProperty(OutputKeys.INDENT, YES);
        trans.transform(new DOMSource(doc), new StreamResult(new File(localFile)));
        return true;
    } catch (TransformerConfigurationException ex) {
        LOG.warn(ERROR_WRITING + localFile, ex);
        return false;
    } catch (TransformerException ex) {
        LOG.warn(ERROR_WRITING + localFile, ex);
        return false;
    }
}

From source file:org.bahmni.module.bahmnicore.web.v1_0.search.BahmniMainResourceControllerTest.java

/**
 * Prints an XML string indented/*  w ww  .  ja  v  a  2 s  . co  m*/
 * 
 * @param xml
 * @throws TransformerException
 */
protected void printXML(String xml) throws TransformerException {

    Source xmlInput = new StreamSource(new StringReader(xml));
    StringWriter stringWriter = new StringWriter();

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(xmlInput, new StreamResult(stringWriter));

    System.out.println(stringWriter.toString());
}

From source file:io.fabric8.tooling.archetype.ArchetypeUtils.java

/**
 * Serializes the Document to a File./*  www .  ja  v  a 2s . c o m*/
 *
 * @param document
 * @param file
 * @throws IOException
 */
public void writeXmlDocument(Document document, File file) throws IOException {
    try {
        Transformer tr = transformerFactory.newTransformer();
        tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        tr.transform(new DOMSource(document), new StreamResult(fileOutputStream));
        fileOutputStream.close();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
}