Move NetconfMessage into netconf.api.messages
[netconf.git] / protocol / netconf-api / src / main / java / org / opendaylight / netconf / api / messages / 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 package org.opendaylight.netconf.api.messages;
9
10 import static java.util.Objects.requireNonNull;
11
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;
22
23 /**
24  * NetconfMessage represents a wrapper around {@link Document}.
25  */
26 public class NetconfMessage {
27     private static final Transformer TRANSFORMER;
28
29     static {
30         final Transformer t;
31         try {
32             t = XmlUtil.newIndentingTransformer();
33         } catch (TransformerConfigurationException e) {
34             throw new ExceptionInInitializerError(e);
35         }
36         t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
37
38         TRANSFORMER = t;
39     }
40
41     private final @NonNull Document document;
42
43     public NetconfMessage(final Document document) {
44         this.document = requireNonNull(document);
45     }
46
47     public final @NonNull Document getDocument() {
48         return document;
49     }
50
51     @Override
52     public final String toString() {
53         final var result = new StreamResult(new StringWriter());
54         final var source = new DOMSource(document.getDocumentElement());
55
56         try {
57             // Slight critical section is a tradeoff. This should be reasonably fast.
58             synchronized (TRANSFORMER) {
59                 TRANSFORMER.transform(source, result);
60             }
61         } catch (TransformerException e) {
62             throw new IllegalStateException("Failed to encode document", e);
63         }
64
65         return result.getWriter().toString();
66     }
67 }