Java Code Examples for org.w3c.dom.Document#setXmlStandalone()

The following examples show how to use org.w3c.dom.Document#setXmlStandalone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IMPBuilder.java    From photon with Apache License 2.0 6 votes vote down vote up
private static DocumentFragment getEssenceDescriptorAsDocumentFragment(RegXMLLibHelper regXMLLibHelper,
                                                                       Document document,
                                                                       KLVPacket.Header essenceDescriptor,
                                                                       List<KLVPacket.Header>subDescriptors,
                                                                       ResourceByteRangeProvider resourceByteRangeProvider,
                                                                       IMFErrorLogger imfErrorLogger) throws MXFException, IOException {
    document.setXmlStandalone(true);

    Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, getByteProvider(resourceByteRangeProvider, essenceDescriptor));
    /*Get the Triplets corresponding to the SubDescriptors*/
    List<Triplet> subDescriptorTriplets = new ArrayList<>();
    for(KLVPacket.Header subDescriptorHeader : subDescriptors){
        subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, getByteProvider(resourceByteRangeProvider, subDescriptorHeader)));
    }
    return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, imfErrorLogger);
}
 
Example 2
Source File: AuctionItemRepository.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the simple case of including a document using xi:include within a
 * xi:fallback using a DocumentBuilder.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackDOMPos() throws Exception {
    String resultFile = USER_DIR + "doc_fallbackDOM.out";
    String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml";
    String xmlFile = XML_DIR + "doc_fallback.xml";
    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 3
Source File: AuctionItemRepository.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test for xi:fallback where the fall back text is parsed as text. This
 * test uses a nested xi:include for the fallback test.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackTextPos() throws Exception {
    String resultFile = USER_DIR + "doc_fallback_text.out";
    String goldFile = GOLDEN_DIR + "doc_fallback_textGold.xml";
    String xmlFile = XML_DIR + "doc_fallback_text.xml";
    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 4
Source File: EppMessageTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void xmlDoctoByteArraySuccess() throws Exception {
  Document xml = builder.newDocument();
  Element doc = xml.createElement("doc");
  Element title = xml.createElement("title");
  title.setTextContent("test");
  Element meta = xml.createElement("meta");
  meta.setAttribute("version", "1.0");
  doc.appendChild(title);
  doc.appendChild(meta);
  xml.appendChild(doc);

  // note that setting the version just ensures this will either be the same in the result,
  // or the result won't support the version and this will throw an exception.
  xml.setXmlVersion("1.0");
  // setting stand alone to true removes this from the processing instructions
  xml.setXmlStandalone(true);
  String expected =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
          + "<doc><title>test</title><meta version=\"1.0\"/></doc>";
  byte[] actual = EppMessage.xmlDocToByteArray(xml);
  assertThat(actual).isEqualTo(expected.getBytes(UTF_8));
}
 
Example 5
Source File: AuctionItemRepository.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test if two non nested xi:include elements can include the same document
 * with an xi:include statement.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeNestedPos() throws Exception {
    String resultFile = USER_DIR + "schedule.out";
    String goldFile = GOLDEN_DIR + "scheduleGold.xml";
    String xmlFile = XML_DIR + "schedule.xml";

    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 6
Source File: EppMessageTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void xmlDocToStringSuccess() throws Exception {
  Document xml = builder.newDocument();
  Element doc = xml.createElement("doc");
  Element title = xml.createElement("title");
  title.setTextContent("test");
  Element meta = xml.createElement("meta");
  meta.setAttribute("version", "1.0");
  doc.appendChild(title);
  doc.appendChild(meta);
  xml.appendChild(doc);

  // note that setting the version just ensures this will either be the same in the result,
  // or the result won't support the version and this will throw an exception.
  xml.setXmlVersion("1.0");
  // setting stand alone to true removes this from the processing instructions
  xml.setXmlStandalone(true);
  String expected =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
          + "<doc><title>test</title><meta version=\"1.0\"/></doc>";
  String actual = EppMessage.xmlDocToString(xml);
  assertThat(actual).isEqualTo(expected);
}
 
Example 7
Source File: JavaxXmlFactories.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public Document newDocumentForSerialization()
{
    try
    {
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        doc.setXmlVersion( "1.1" );
        doc.setXmlStandalone( true );
        return doc;
    }
    catch( ParserConfigurationException ex )
    {
        throw new SerializationException( "Unable to create XML document. "
                                          + "Is your javax.xml subsystem correctly set up?", ex );
    }
}
 
Example 8
Source File: XmlDomWriter.java    From AndroidStarterKit with MIT License 6 votes vote down vote up
public void writeDocument(File file, Document document) throws TransformerException, IOException {
  document.setXmlStandalone(true);

  TransformerFactory tf = TransformerFactory.newInstance();
  tf.setAttribute("indent-number", new Integer(4));

  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  DOMSource source = new DOMSource(document);

  FileWriter fileWriter = new FileWriter(file);
  StreamResult writeStream = new StreamResult(fileWriter);

  transformer.transform(source, writeStream);
}
 
Example 9
Source File: AndroidStringsXmlWriter.java    From mojito with Apache License 2.0 5 votes vote down vote up
private static Document toDocument(List<AndroidStringsTextUnit> androidStringsTextUnitList, String pluralNameSeparator) throws ParserConfigurationException {
    Document document = getDocumentBuilder().newDocument();
    document.setXmlStandalone(true);
    Node node = document.createElement(ROOT_ELEMENT_NAME);
    document.appendChild(node);

    List<AndroidStringsTextUnit> sortedAndroidStringsTextUnitList = androidStringsTextUnitList.stream().sorted(Comparator.comparing(AndroidStringsTextUnit::getName)).collect(Collectors.toList());
    for (int i = 0; i < sortedAndroidStringsTextUnitList.size(); i++) {
        if (sortedAndroidStringsTextUnitList.get(i).getPluralForm() == null) {
            addSingularString(document, node, sortedAndroidStringsTextUnitList.get(i));
        } else {
            String pluralName = getPluralName(sortedAndroidStringsTextUnitList.get(i));
            node = addPluralString(document, node, sortedAndroidStringsTextUnitList.get(i), pluralNameSeparator);
            List<AndroidStringsTextUnit> pluralList = new ArrayList<>();
            for (; i < sortedAndroidStringsTextUnitList.size() && Objects.equals(pluralName, getPluralName(sortedAndroidStringsTextUnitList.get(i))); i++) {
                pluralList.add(sortedAndroidStringsTextUnitList.get(i));
            }
            pluralList.sort(Comparator.comparingInt(item -> PluralItem.valueOf(item.getPluralForm()).ordinal()));
            addPluralList(document, node, pluralList);

            i -= 1;
            node = node.getParentNode();
        }
    }

    return document;
}
 
Example 10
Source File: AbstractApplicationComposition.java    From photon with Apache License 2.0 5 votes vote down vote up
private DocumentFragment getEssenceDescriptorAsDocumentFragment(Document document, Composition.HeaderPartitionTuple headerPartitionTuple, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header> subDescriptors) throws MXFException, IOException {
    document.setXmlStandalone(true);

    PrimerPack primerPack = headerPartitionTuple.getHeaderPartition().getPrimerPack();
    ResourceByteRangeProvider resourceByteRangeProvider = headerPartitionTuple.getResourceByteRangeProvider();
    RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(primerPack.getHeader(), getByteProvider(resourceByteRangeProvider, primerPack.getHeader()));
    Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, getByteProvider(resourceByteRangeProvider, essenceDescriptor));
    //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document);
    /*Get the Triplets corresponding to the SubDescriptors*/
    List<Triplet> subDescriptorTriplets = new ArrayList<>();
    for (KLVPacket.Header subDescriptorHeader : subDescriptors) {
        subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.getByteProvider(resourceByteRangeProvider, subDescriptorHeader)));
    }
    return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, this.imfErrorLogger);
}
 
Example 11
Source File: MXFEssenceReader.java    From photon with Apache License 2.0 5 votes vote down vote up
private DocumentFragment getEssenceDescriptorAsDocumentFragment(Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors) throws MXFException, IOException {
    document.setXmlStandalone(true);

    PrimerPack primerPack = this.getHeaderPartition().getPrimerPack();
    RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(primerPack.getHeader(), this.getByteProvider(primerPack.getHeader()));
    Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor, this.getByteProvider(essenceDescriptor));
    //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document);
    /*Get the Triplets corresponding to the SubDescriptors*/
    List<Triplet> subDescriptorTriplets = new ArrayList<>();
    for(KLVPacket.Header subDescriptorHeader : subDescriptors){
        subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.getByteProvider(subDescriptorHeader)));
    }
    return regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, this.imfErrorLogger);
}
 
Example 12
Source File: DLNAService.java    From Connect-SDK-Android-Core with Apache License 2.0 5 votes vote down vote up
protected String getMessageXml(String serviceURN, String method, String instanceId, Map<String, String> params) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        doc.setXmlStandalone(true);
        doc.setXmlVersion("1.0");

        Element root = doc.createElement("s:Envelope");
        Element bodyElement = doc.createElement("s:Body");
        Element methodElement = doc.createElementNS(serviceURN, "u:" + method);
        Element instanceElement = doc.createElement("InstanceID");

        root.setAttribute("s:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
        root.setAttribute("xmlns:s", "http://schemas.xmlsoap.org/soap/envelope/");

        doc.appendChild(root);
        root.appendChild(bodyElement);
        bodyElement.appendChild(methodElement);
        if (instanceId != null) {
            instanceElement.setTextContent(instanceId);
            methodElement.appendChild(instanceElement);
        }

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Element element = doc.createElement(key);
                element.setTextContent(value);
                methodElement.appendChild(element);
            }
        }
        return xmlToString(doc, true);
    } catch (Exception e) {
        return null;
    }
}
 
Example 13
Source File: XmlUtils.java    From knox with Apache License 2.0 5 votes vote down vote up
public static Document createDocument(boolean standalone) throws ParserConfigurationException {
  DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
  f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
  f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  DocumentBuilder b = f.newDocumentBuilder();
  Document d = b.newDocument();
  d.setXmlStandalone( standalone );
  return d;
}
 
Example 14
Source File: Jsons2Xsd.java    From jsons2xsd with MIT License 5 votes vote down vote up
private static Element createDocument(Config cfg)
{
    final Document xsdDoc = XmlUtil.newDocument();
    xsdDoc.setXmlStandalone(true);

    final Element schemaRoot = element(xsdDoc, "schema");
    schemaRoot.setAttribute("targetNamespace", cfg.getTargetNamespace());
    schemaRoot.setAttribute("xmlns:" + cfg.getNsAlias(), cfg.getTargetNamespace());
    schemaRoot.setAttribute("elementFormDefault", "qualified");
    if (cfg.isAttributesQualified())
    {
        schemaRoot.setAttribute("attributeFormDefault", "qualified");
    }
    return schemaRoot;
}
 
Example 15
Source File: Config.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public void write(OutputStream out) throws ApplicationException
{
    try
    {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        doc.setXmlStandalone(true);
        Element el = doc.createElement("boost_serialization");
        doc.appendChild(el);
        el.setAttribute("signature", "serialization::archive");
        el.setAttribute("version", "14");
        el.appendChild(makeCfgElement(doc));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "boost_serialization");
        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
    }
    catch (Exception e)
    {
        throw new ApplicationException("Failed making EncFs config file", e);
    }
}
 
Example 16
Source File: SpringBootStarterMojo.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private void writeXmlFormatted(Document pom, File destination) throws Exception {
    XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyNodes = (NodeList) xpath.evaluate(pom, XPathConstants.NODESET);

    // Remove empty text nodes
    for (int i = 0; i < emptyNodes.getLength(); i++) {
        Node emptyNode = emptyNodes.item(i);
        emptyNode.getParentNode().removeChild(emptyNode);
    }

    pom.setXmlStandalone(true);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(pom);

    String content;
    try (StringWriter out = new StringWriter()) {
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        content = out.toString();
    }

    // Fix header formatting problem
    content = content.replaceFirst("-->", "-->\n").replaceFirst("\\?><!--", "\\?>\n<!--");

    writeIfChanged(content, destination);
}
 
Example 17
Source File: XMLSchemaBuilder.java    From regxmllib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Generates a single XML Schema document from a single Metadictionary. A
 * definition from the latter may reference a definition from another
 * Metadictionary, i.e. in a different namespace, as long as this second
 * Metadictionary can be resolved by the {@link DefinitionResolver} provided
 * a creation-time.
 *
 * @param dict Metadictionary for which an XML Schema will be generated.
 *
 * @return XML Schema document
 *
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws com.sandflow.smpte.klv.exceptions.KLVException
 * @throws com.sandflow.smpte.regxml.XMLSchemaBuilder.RuleException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public Document fromDictionary(MetaDictionary dict) throws ParserConfigurationException, KLVException, RuleException, SAXException, IOException {

    /* reset namespace prefixes */
    this.prefixes.clear();

    /* create the DOM from the STD_DECL template */
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.newDocument();

    doc.setXmlStandalone(true);

    Element schema = doc.createElementNS(XSD_NS, "xs:schema");
    schema.setAttribute("targetNamespace", dict.getSchemeURI().toString());
    schema.setAttributeNS(XMLNS_NS, "xmlns:reg", REGXML_NS);
    schema.setAttributeNS(XMLNS_NS, "xmlns:xlink", XLINK_NS);
    schema.setAttribute("elementFormDefault", "qualified");
    schema.setAttribute("attributeFormDefault", "unqualified");
    doc.appendChild(schema);

    Element importelem = doc.createElementNS(XSD_NS, "xs:import");
    importelem.setAttribute("namespace", XLINK_NS);
    importelem.setAttribute("schemaLocation", XLINK_LOC);
    doc.getDocumentElement().appendChild(importelem);

    importelem = doc.createElementNS(XSD_NS, "xs:import");
    importelem.setAttribute("namespace", REGXML_NS);
    doc.getDocumentElement().appendChild(importelem);

    for (Definition definition : dict.getDefinitions()) {

        if (definition instanceof ClassDefinition) {

            applyRule4(doc.getDocumentElement(), (ClassDefinition) definition);

        } else if (definition.getClass() == PropertyDefinition.class) {

            applyRule5(doc.getDocumentElement(), (PropertyDefinition) definition);

        } else if (definition.getClass() == PropertyAliasDefinition.class) {

            /* need to supress alias declaration since they use the same symbol and AUID as parent */
        } else {
            applyRule6(doc.getDocumentElement(), definition);
        }
    }

    /* hack to clean-up namespace prefixes */
    for (URI uri : prefixes.getURIs()) {

        doc.getDocumentElement().setAttributeNS(
            XMLNS_NS,
            "xmlns:" + prefixes.getPrefixOrCreate(uri),
            uri.toString()
        );

        if (!uri.equals(dict.getSchemeURI())) {
            importelem = doc.createElementNS(XSD_NS, "xs:import");
            importelem.setAttribute("namespace", uri.toString());
            doc.getDocumentElement().insertBefore(importelem, doc.getDocumentElement().getFirstChild());

        }
    }

    return doc;
}
 
Example 18
Source File: WorkspaceUpdater.java    From buck with Apache License 2.0 4 votes vote down vote up
private static Document createNewWorkspaceDocument() throws ParserConfigurationException {
  Document workspaceDocument = createDocumentBuilder().newDocument();
  workspaceDocument.setXmlStandalone(true);
  return workspaceDocument;
}
 
Example 19
Source File: PreferencesService.java    From latexdraw with GNU General Public License v3.0 4 votes vote down vote up
public void writePreferences() {
	final Optional<Document> opt = SystemUtils.getInstance().createXMLDocumentBuilder().map(b -> b.newDocument());

	if(opt.isEmpty()) {
		return;
	}

	final Document document = opt.get();
	final Element root = document.createElement(LNamespace.XML_ROOT_PREFERENCES);

	document.setXmlVersion("1.0"); //NON-NLS
	document.setXmlStandalone(true);
	document.appendChild(root);

	final Attr attr = document.createAttribute(LNamespace.XML_VERSION);
	attr.setTextContent(VersionChecker.VERSION);
	root.setAttributeNode(attr);

	SystemUtils.getInstance().createElement(document, LNamespace.XML_PATH_EXPORT, pathExport.get(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_PATH_OPEN, pathOpen.get(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_UNIT, unit.get().name(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_PAGE, page.get().name(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_CHECK_VERSION, String.valueOf(checkVersion.get()), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_LANG, lang.get().toLanguageTag(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_MAGNETIC_GRID, String.valueOf(magneticGrid.get()), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_GRID_STYLE, gridStyle.get().name(), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_GRID_GAP, String.valueOf(gridGap.get()), root);
	SystemUtils.getInstance().createElement(document, LNamespace.XML_LATEX_INCLUDES, includes.get(), root);
	final Element recent = document.createElement(LNamespace.XML_RECENT_FILES);
	root.appendChild(recent);
	recent.setAttribute(LNamespace.XML_NB_RECENT_FILES, String.valueOf(nbRecentFiles.get()));
	recentFileNames.forEach(n -> SystemUtils.getInstance().createElement(document, LNamespace.XML_RECENT_FILE, n, recent));

	try {
		try(final OutputStream fos = Files.newOutputStream(Path.of(getPreferencesPath()))) {
			final Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //NON-NLS
			transformer.transform(new DOMSource(document), new StreamResult(fos));
		}
	}catch(final TransformerException | IllegalArgumentException | DOMException | IOException | FactoryConfigurationError ex) {
		BadaboomCollector.INSTANCE.add(ex);
	}
}
 
Example 20
Source File: IMFTrackFileCPLBuilder.java    From photon with Apache License 2.0 3 votes vote down vote up
/**
 * A method that returns a XML file representing a MXF EssenceDescriptor present in the IMF Essence.
 *
 * @return An XML DOM Document fragment representing the EssenceDescriptors contained in the MXF file
 * @throws IOException - any I/O related error will be exposed through an IOException,
 * @throws MXFException - any MXF standard related non-compliance will be exposed through a MXF exception
 * @throws TransformerException - any XML transformation critical error will be exposed through a TransformerException
 */
File getEssenceDescriptorAsXMLFile(Document document, KLVPacket.Header essenceDescriptor, List<KLVPacket.Header>subDescriptors, IMFErrorLogger imfErrorLogger) throws MXFException, IOException,
        TransformerException {

    File outputFile = new File(this.workingDirectory + "/" + "EssenceDescriptor.xml");

    document.setXmlStandalone(true);


    DocumentFragment documentFragment = getEssenceDescriptorAsDocumentFragment(document, essenceDescriptor, subDescriptors, imfErrorLogger);
    document.appendChild(documentFragment);

    /* write DOM to file */
    Transformer tr = TransformerFactory.newInstance().newTransformer();

    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    /*tr.transform(
            new DOMSource(document),
            new StreamResult(System.out)
    );*/

    tr.transform(
            new DOMSource(document),
            new StreamResult(outputFile)
    );


    return outputFile;
}