Merge "Use Preconditions"
[controller.git] / opendaylight / netconf / netconf-api / src / main / java / org / opendaylight / controller / netconf / api / NetconfMessage.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.api;
10
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;
21
22 /**
23  * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for
24  * implementing ProtocolMessage interface.
25  */
26 public class NetconfMessage {
27     private static final Transformer TRANSFORMER;
28
29     static {
30         final Transformer t;
31         try {
32             t = TransformerFactory.newInstance().newTransformer();
33         } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
34             throw new ExceptionInInitializerError(e);
35         }
36         t.setOutputProperty(OutputKeys.INDENT, "yes");
37         t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
38
39         TRANSFORMER = t;
40     }
41
42     private final Document doc;
43
44     public NetconfMessage(final Document doc) {
45         this.doc = doc;
46     }
47
48     public Document getDocument() {
49         return this.doc;
50     }
51
52     @Override
53     public String toString() {
54         final StreamResult result = new StreamResult(new StringWriter());
55         final DOMSource source = new DOMSource(doc.getDocumentElement());
56
57         try {
58             // Slight critical section is a tradeoff. This should be reasonably fast.
59             synchronized (TRANSFORMER) {
60                 TRANSFORMER.transform(source, result);
61             }
62         } catch (TransformerException e) {
63             throw new IllegalStateException("Failed to encode document", e);
64         }
65
66         return result.getWriter().toString();
67     }
68 }