Remove netconf from commons/opendaylight pom
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / 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.nettyutil.handler;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.ByteBufOutputStream;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.MessageToByteEncoder;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.io.OutputStreamWriter;
19 import javax.xml.transform.TransformerException;
20 import javax.xml.transform.dom.DOMSource;
21 import javax.xml.transform.stream.StreamResult;
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.w3c.dom.Comment;
26
27 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
28     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
29
30     private final Optional<String> clientId;
31
32     public NetconfMessageToXMLEncoder() {
33         this(Optional.<String>absent());
34     }
35
36     public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
37         this.clientId = clientId;
38     }
39
40     @Override
41     @VisibleForTesting
42     public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws IOException, TransformerException {
43         LOG.trace("Sent to encode : {}", msg);
44
45         if (clientId.isPresent()) {
46             Comment comment = msg.getDocument().createComment("clientId:" + clientId.get());
47             msg.getDocument().appendChild(comment);
48         }
49
50         try (OutputStream os = new ByteBufOutputStream(out)) {
51             // Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
52
53             // Using custom BufferedWriter that does not provide newLine method as performance improvement
54             // see javadoc for org.opendaylight.controller.netconf.nettyutil.handler.BufferedWriter
55             StreamResult result = new StreamResult(new org.opendaylight.controller.netconf.nettyutil.handler.BufferedWriter(new OutputStreamWriter(os)));
56             DOMSource source = new DOMSource(msg.getDocument());
57             ThreadLocalTransformers.getPrettyTransformer().transform(source, result);
58         }
59     }
60 }