Merge "Changed model versions to dependencies"
[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.channel.ChannelHandlerContext;
12 import io.netty.handler.codec.MessageToByteEncoder;
13
14 import java.nio.ByteBuffer;
15
16 import org.opendaylight.controller.netconf.api.NetconfMessage;
17 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20 import org.w3c.dom.Comment;
21 import org.w3c.dom.Document;
22
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.common.base.Charsets;
25 import com.google.common.base.Optional;
26
27 public final 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(Optional<String> clientId) {
37         this.clientId = clientId;
38     }
39
40     @Override
41     @VisibleForTesting
42     public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws Exception {
43         LOG.debug("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         final ByteBuffer msgBytes;
51         if(msg.getAdditionalHeader().isPresent()) {
52             final String header = msg.getAdditionalHeader().get();
53             LOG.trace("Header of netconf message parsed \n{}", header);
54             // FIXME: this can be written in pieces
55             msgBytes = Charsets.UTF_8.encode(header + xmlToString(msg.getDocument()));
56         } else {
57             msgBytes = Charsets.UTF_8.encode(xmlToString(msg.getDocument()));
58         }
59
60         LOG.trace("Putting message \n{}", xmlToString(msg.getDocument()));
61         out.writeBytes(msgBytes);
62     }
63
64     private String xmlToString(Document doc) {
65         return XmlUtil.toString(doc, false);
66     }
67 }