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.nettyutil.handler;
10 import com.google.common.base.Preconditions;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.ByteBufInputStream;
13 import io.netty.buffer.ByteBufUtil;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.ByteToMessageDecoder;
16 import java.io.InputStream;
17 import java.util.List;
18 import javax.xml.transform.TransformerFactory;
19 import javax.xml.transform.dom.DOMResult;
20 import javax.xml.transform.sax.SAXTransformerFactory;
21 import javax.xml.transform.sax.TransformerHandler;
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.openexi.sax.EXIReader;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Document;
27 import org.xml.sax.InputSource;
29 public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
31 private static final Logger LOG = LoggerFactory.getLogger(NetconfEXIToMessageDecoder.class);
33 private final NetconfEXICodec codec;
35 public NetconfEXIToMessageDecoder(final NetconfEXICodec codec) {
36 this.codec = Preconditions.checkNotNull(codec);
40 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
42 * Note that we could loop here and process all the messages, but we can't do that.
43 * The reason is <stop-exi> operation, which has the contract of immediately stopping
44 * the use of EXI, which means the next message needs to be decoded not by us, but rather
48 // If empty Byte buffer is passed to r.parse, EOFException is thrown
49 if (in.isReadable() == false) {
50 LOG.debug("No more content in incoming buffer.");
54 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
56 final EXIReader r = codec.getReader();
58 final SAXTransformerFactory transformerFactory
59 = (SAXTransformerFactory) TransformerFactory.newInstance();
60 final TransformerHandler handler = transformerFactory.newTransformerHandler();
61 r.setContentHandler(handler);
63 final DOMResult domResult = new DOMResult();
64 handler.setResult(domResult);
66 try (final InputStream is = new ByteBufInputStream(in)) {
67 r.parse(new InputSource(is));
70 out.add(new NetconfMessage((Document) domResult.getNode()));