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
9 package org.opendaylight.netconf.api;
11 import java.io.StringWriter;
12 import javax.xml.transform.OutputKeys;
13 import javax.xml.transform.Transformer;
14 import javax.xml.transform.TransformerConfigurationException;
15 import javax.xml.transform.TransformerException;
16 import javax.xml.transform.TransformerFactory;
17 import javax.xml.transform.TransformerFactoryConfigurationError;
18 import javax.xml.transform.dom.DOMSource;
19 import javax.xml.transform.stream.StreamResult;
20 import org.w3c.dom.Document;
23 * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for
24 * implementing ProtocolMessage interface.
26 public class NetconfMessage {
27 private static final Transformer TRANSFORMER;
32 t = TransformerFactory.newInstance().newTransformer();
33 } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
34 throw new ExceptionInInitializerError(e);
36 t.setOutputProperty(OutputKeys.INDENT, "yes");
37 t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
42 private final Document doc;
44 public NetconfMessage() {
45 // Required for FailedNetconfMessage
49 public NetconfMessage(final Document doc) {
53 public Document getDocument() {
58 public String toString() {
59 final StreamResult result = new StreamResult(new StringWriter());
60 final DOMSource source = new DOMSource(doc.getDocumentElement());
63 // Slight critical section is a tradeoff. This should be reasonably fast.
64 synchronized (TRANSFORMER) {
65 TRANSFORMER.transform(source, result);
67 } catch (TransformerException e) {
68 throw new IllegalStateException("Failed to encode document", e);
71 return result.getWriter().toString();