Skip to contentPackage: Documents
Documents
Coverage
1: /*******************************************************************************
2: * Copyright (c) 2017, 2022 Red Hat Inc and others
3: *
4: * This program and the accompanying materials are made
5: * available under the terms of the Eclipse Public License 2.0
6: * which is available at https://www.eclipse.org/legal/epl-2.0/
7: *
8: * SPDX-License-Identifier: EPL-2.0
9: *
10: * Contributors:
11: * Red Hat Inc - initial API and implementation
12: *******************************************************************************/
13: package org.eclipse.kapua.kura.simulator.util;
14:
15: import java.io.StringWriter;
16: import java.io.Writer;
17: import java.util.function.Consumer;
18:
19: import javax.xml.XMLConstants;
20: import javax.xml.parsers.DocumentBuilder;
21: import javax.xml.parsers.DocumentBuilderFactory;
22: import javax.xml.parsers.ParserConfigurationException;
23: import javax.xml.transform.Transformer;
24: import javax.xml.transform.TransformerException;
25: import javax.xml.transform.TransformerFactory;
26: import javax.xml.transform.dom.DOMSource;
27: import javax.xml.transform.stream.StreamResult;
28:
29: import org.w3c.dom.Document;
30:
31: public final class Documents {
32:
33: private Documents() {
34: }
35:
36: public static String create(final Consumer<Document> documentBuilder)
37: throws ParserConfigurationException, TransformerException {
38: final StringWriter sw = new StringWriter();
39: create(documentBuilder, sw);
40: return sw.toString();
41: }
42:
43: public static void create(final Consumer<Document> documentBuilder, final Writer writer)
44: throws ParserConfigurationException, TransformerException {
45: final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
46: dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Sonar java:S2755
47: dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Sonar java:S2755
48: final DocumentBuilder db = dbf.newDocumentBuilder();
49: final Document doc = db.newDocument();
50:
51: documentBuilder.accept(doc);
52:
53: final TransformerFactory tf = TransformerFactory.newInstance();
54: tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Sonar java:S2755
55: tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); // Sonar java:S2755
56: final Transformer t = tf.newTransformer();
57:
58: t.transform(new DOMSource(doc), new StreamResult(writer));
59: }
60: }