2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.netconf.util.handler;
10 import io.netty.buffer.ByteBuf;
11 import io.netty.channel.ChannelHandlerContext;
12 import io.netty.handler.codec.MessageToByteEncoder;
14 import java.nio.ByteBuffer;
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;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.common.base.Charsets;
25 import com.google.common.base.Optional;
27 public final class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
28 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
30 private final Optional<String> clientId;
32 public NetconfMessageToXMLEncoder() {
33 this(Optional.<String>absent());
36 public NetconfMessageToXMLEncoder(Optional<String> clientId) {
37 this.clientId = clientId;
42 public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws Exception {
43 LOG.debug("Sent to encode : {}", msg);
45 if (clientId.isPresent()) {
46 Comment comment = msg.getDocument().createComment("clientId:" + clientId.get());
47 msg.getDocument().appendChild(comment);
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()));
57 msgBytes = Charsets.UTF_8.encode(xmlToString(msg.getDocument()));
60 LOG.trace("Putting message \n{}", xmlToString(msg.getDocument()));
61 out.writeBytes(msgBytes);
64 private String xmlToString(Document doc) {
65 return XmlUtil.toString(doc, false);