Improve NETCONF encoding performance
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfMessageToXMLEncoder.java
1 /*
2  * Copyright (c) 2014 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.controller.netconf.util.handler;
9
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.ByteBufOutputStream;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.MessageToByteEncoder;
14
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.io.OutputStreamWriter;
18
19 import javax.xml.transform.OutputKeys;
20 import javax.xml.transform.Transformer;
21 import javax.xml.transform.TransformerException;
22 import javax.xml.transform.TransformerFactory;
23 import javax.xml.transform.dom.DOMSource;
24 import javax.xml.transform.stream.StreamResult;
25
26 import org.opendaylight.controller.netconf.api.NetconfMessage;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.w3c.dom.Comment;
30
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Optional;
33
34 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
35     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
36     private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
37
38     private final Optional<String> clientId;
39
40     public NetconfMessageToXMLEncoder() {
41         this(Optional.<String>absent());
42     }
43
44     public NetconfMessageToXMLEncoder(Optional<String> clientId) {
45         this.clientId = clientId;
46     }
47
48     @Override
49     @VisibleForTesting
50     public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
51         LOG.debug("Sent to encode : {}", msg);
52
53         if (clientId.isPresent()) {
54             Comment comment = msg.getDocument().createComment("clientId:" + clientId.get());
55             msg.getDocument().appendChild(comment);
56         }
57
58         try (OutputStream os = new ByteBufOutputStream(out)) {
59             Transformer transformer = FACTORY.newTransformer();
60             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
61             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
62
63             StreamResult result = new StreamResult(new OutputStreamWriter(os));
64             DOMSource source = new DOMSource(msg.getDocument());
65             transformer.transform(source, result);
66         }
67     }
68 }