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.controller.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(final Document doc) {
48 public Document getDocument() {
53 public String toString() {
54 final StreamResult result = new StreamResult(new StringWriter());
55 final DOMSource source = new DOMSource(doc.getDocumentElement());
58 // Slight critical section is a tradeoff. This should be reasonably fast.
59 synchronized (TRANSFORMER) {
60 TRANSFORMER.transform(source, result);
62 } catch (TransformerException e) {
63 throw new IllegalStateException("Failed to encode document", e);
66 return result.getWriter().toString();