Bug 8824 - NETCONF request hangs when rpc-rply has invalid xml
[netconf.git] / netconf / netconf-api / src / main / java / org / opendaylight / 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.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() {
45         // Required for FailedNetconfMessage
46         this.doc = null;
47     }
48
49     public NetconfMessage(final Document doc) {
50         this.doc = doc;
51     }
52
53     public Document getDocument() {
54         return this.doc;
55     }
56
57     @Override
58     public String toString() {
59         final StreamResult result = new StreamResult(new StringWriter());
60         final DOMSource source = new DOMSource(doc.getDocumentElement());
61
62         try {
63             // Slight critical section is a tradeoff. This should be reasonably fast.
64             synchronized (TRANSFORMER) {
65                 TRANSFORMER.transform(source, result);
66             }
67         } catch (TransformerException e) {
68             throw new IllegalStateException("Failed to encode document", e);
69         }
70
71         return result.getWriter().toString();
72     }
73 }