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.alfaariss.oa.util.configuration.handler.file.FileConfigurationHandler.java

/**
 * Save the configuration to the file./*  w w  w. jav  a2  s . c  om*/
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 */
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    OutputStream os = null;
    try {
        os = new FileOutputStream(_fConfig);
        //create output format which uses new lines and tabs

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os));
    } catch (FileNotFoundException e) {
        _logger.error("Error writing configuration, file not found", e);
        throw new ConfigurationException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } finally {

        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            _logger.debug("Error closing configuration outputstream", e);
        }
    }
}

From source file:com.mirth.connect.model.converters.DICOMSerializer.java

@Override
public String toXML(String source) throws SerializerException {
    try {//from   w  ww  .j av a2 s  . c  o m
        DicomObject dicomObject = DICOMUtil.byteArrayToDicomObject(Base64.decodeBase64(source));
        // read in header and pixel data
        pixelData = extractPixelDataFromDicomObject(dicomObject);
        byte[] decodedMessage = DICOMUtil.dicomObjectToByteArray(dicomObject);
        rawData = new String(Base64.encodeBase64Chunked(decodedMessage));

        StringWriter output = new StringWriter();
        DicomInputStream dis = new DicomInputStream(new ByteArrayInputStream(decodedMessage));

        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 SerializerException(e);
    }
}

From source file:com.datatorrent.stram.client.DTConfiguration.java

public void writeToFile(File file, Scope scope, String comment) throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = new Date();
    Document doc;/*from  w w w  .j  a  v a  2  s.  co  m*/
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    }
    Element rootElement = doc.createElement("configuration");
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));
    rootElement.appendChild(doc.createComment(" Written by dtgateway on " + sdf.format(date)));
    rootElement.appendChild(doc.createComment(" " + comment + " "));
    doc.appendChild(rootElement);
    for (Map.Entry<String, ValueEntry> entry : map.entrySet()) {
        ValueEntry valueEntry = entry.getValue();
        if (scope == null || valueEntry.scope == scope) {
            Element property = doc.createElement("property");
            rootElement.appendChild(property);
            Element name = doc.createElement("name");
            name.appendChild(doc.createTextNode(entry.getKey()));
            property.appendChild(name);
            Element value = doc.createElement("value");
            value.appendChild(doc.createTextNode(valueEntry.value));
            property.appendChild(value);
            if (valueEntry.description != null) {
                Element description = doc.createElement("description");
                description.appendChild(doc.createTextNode(valueEntry.description));
                property.appendChild(description);
            }
            if (valueEntry.isFinal) {
                Element isFinal = doc.createElement("final");
                isFinal.appendChild(doc.createTextNode("true"));
                property.appendChild(isFinal);
            }
        }
    }
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));

    // write the content into xml file
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file);
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}

From source file:com.redhat.akashche.wixgen.cli.Launcher.java

private static void transformWithXsl(String inputPath, String xslPath, String outputPath) throws Exception {
    File file = new File(outputPath);
    if (file.exists())
        throw new IOException("Output file already exists: [" + outputPath + "]");
    TransformerFactory factory = TransformerFactory.newInstance();
    Source xsl = new StreamSource(new File(xslPath));
    Transformer transformer = factory.newTransformer(xsl);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    Source text = new StreamSource(new File(inputPath));
    transformer.transform(text, new StreamResult(new File(outputPath)));
}

From source file:com.onespatial.jrc.tns.oml_to_rif.fixture.DomBasedUnitTest.java

/**
 * Pretty Print a DOM to a stream./*from w  w  w. j  a v  a  2s.com*/
 * 
 * @param document
 *            the DOM to print.
 * @param dest
 *            the stream to write to.
 */
protected void writeDom(Document document, OutputStream dest) {
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(dest);
    try {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
        fail();
    }
}

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

/**
 * Convert a DOM document to a string//from  w  w w  .  java  2  s.  co  m
 *
 * @param doc
 * @return
 * @throws TransformerException
 */
public static String convertDocToString(Document doc) throws TransformerException {
    //set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
    trans.setOutputProperty(OutputKeys.INDENT, YES);

    //create string from xml tree
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    return sw.toString();
}

From source file:com.stratelia.webactiv.util.XMLConfigurationStore.java

@Override
public void serialize() throws FileNotFoundException, IOException {
    FileOutputStream out = new FileOutputStream(new File(configFileName));
    StreamResult streamResult = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer;//from www. j  av  a 2 s .  c  o m
    try {
        serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, CharEncoding.UTF_8);
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        DOMSource domSource = new DOMSource(xmlConfigDOMDoc);
        serializer.transform(domSource, streamResult);
    } catch (TransformerException ex) {
        Logger.getLogger(XMLConfigurationStore.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:channellistmaker.channelfilemaker.ChannelDocumentMaker.java

/**
 * @return ????X???ML????????//from  w w  w . java2  s  . co m
 */
public String getChannelList() {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document document = db.newDocument();
        // >>>>> DOM??
        Element channels_e = document.createElement("channels");//<-root
        document.appendChild(channels_e);

        final Set<MultiKey<Integer>> keys = this.channels.keySet();
        for (MultiKey<Integer> key : keys) {
            Channel ch = channels.get(key);
            this.addChannelElement(document, channels_e, ch);
        }

        TransformerFactory tf = TransformerFactory.newInstance();

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter writer = new StringWriter();// <-??????????
        StreamResult result = new StreamResult(writer);

        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);

        return writer.toString();
    } catch (ParserConfigurationException | TransformerConfigurationException ex) {
        LOG.fatal(ex);
        return "";
    } catch (TransformerException ex) {
        LOG.fatal(ex);
        return "";
    }
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Write the given xml document to the outputFile.
 *
 * @param document the xml document//w  ww.ja v a  2 s. c  o m
 * @param outputFile the output file
 */
public static void writeToFile(Document document, File outputFile) {
    try {
        TransformerFactory transfac = TransformerFactory.newInstance();
        transfac.setAttribute("indent-number", 2);
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource domSource = new DOMSource(document);
        BufferedOutputStream bw = null;
        try {
            outputFile.getParentFile().mkdirs();
            log.info("Writing to file {}", outputFile.getAbsolutePath());
            bw = new BufferedOutputStream(new FileOutputStream(outputFile));
            trans.transform(domSource, new StreamResult(new OutputStreamWriter(bw, "utf-8")));
            bw.close();
        } catch (IOException ex) {
            Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException ex) {
                    Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
            }
        }

        //System.out.println(xmlString);
    } catch (TransformerException ex) {
        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

@Autowired
public DocumentResource(FedoraRepository fedoraRepository, URNConfiguration urnConfiguration,
        FileHandlingService fileHandlingService)
        throws ParserConfigurationException, TransformerConfigurationException {
    this.fedoraRepository = fedoraRepository;
    this.urnConfiguration = urnConfiguration;
    this.fileHandlingService = fileHandlingService;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    xmlOutputFactory = XMLOutputFactory.newFactory();
}