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 java.io.ByteArrayInputStream;
11 import java.nio.ByteBuffer;
12 import java.util.List;
14 import org.opendaylight.controller.netconf.api.NetconfDeserializerException;
15 import org.opendaylight.controller.netconf.api.NetconfMessage;
16 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import org.w3c.dom.Document;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Charsets;
24 import io.netty.buffer.ByteBuf;
25 import io.netty.buffer.ByteBufUtil;
26 import io.netty.channel.ChannelHandlerContext;
27 import io.netty.handler.codec.ByteToMessageDecoder;
29 public class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
30 private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class);
34 public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
35 if (in.readableBytes() == 0) {
36 LOG.debug("No more content in incoming buffer.");
42 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
43 byte[] bytes = new byte[in.readableBytes()];
48 bytes = preprocessMessageBytes(bytes);
49 NetconfMessage message;
51 Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
52 message = buildNetconfMessage(doc);
53 } catch (Exception e) {
54 throw new NetconfDeserializerException("Could not parse message from " + new String(bytes), e);
59 in.discardReadBytes();
64 protected void cleanUpAfterDecode() {}
66 protected NetconfMessage buildNetconfMessage(Document doc) {
67 return new NetconfMessage(doc);
70 protected byte[] preprocessMessageBytes(byte[] bytes) {
74 private void logMessage(byte[] bytes) {
75 String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
76 LOG.debug("Parsing message \n{}", s);