2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.api.messages;
10 import static java.util.Objects.requireNonNull;
12 import java.io.StringWriter;
13 import javax.xml.transform.OutputKeys;
14 import javax.xml.transform.Transformer;
15 import javax.xml.transform.TransformerConfigurationException;
16 import javax.xml.transform.TransformerException;
17 import javax.xml.transform.dom.DOMSource;
18 import javax.xml.transform.stream.StreamResult;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.netconf.api.xml.XmlUtil;
21 import org.w3c.dom.Document;
24 * NetconfMessage represents a wrapper around {@link Document}.
26 public class NetconfMessage {
27 private static final Transformer TRANSFORMER;
32 t = XmlUtil.newIndentingTransformer();
33 } catch (TransformerConfigurationException e) {
34 throw new ExceptionInInitializerError(e);
36 t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
41 private final @NonNull Document document;
43 public NetconfMessage(final Document document) {
44 this.document = requireNonNull(document);
47 public final @NonNull Document getDocument() {
52 public final String toString() {
53 final var result = new StreamResult(new StringWriter());
54 final var source = new DOMSource(document.getDocumentElement());
57 // Slight critical section is a tradeoff. This should be reasonably fast.
58 synchronized (TRANSFORMER) {
59 TRANSFORMER.transform(source, result);
61 } catch (TransformerException e) {
62 throw new IllegalStateException("Failed to encode document", e);
65 return result.getWriter().toString();