e4c14abeaaf3dbc8bc463e2fbb93ef056c65cf8a
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfEXIToMessageDecoder.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.buffer.ByteBufInputStream;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14
15 import java.io.InputStream;
16 import java.util.List;
17
18 import javax.xml.transform.dom.DOMResult;
19 import javax.xml.transform.sax.SAXTransformerFactory;
20 import javax.xml.transform.sax.TransformerHandler;
21
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.openexi.sax.EXIReader;
24 import org.w3c.dom.Document;
25 import org.xml.sax.InputSource;
26
27 import com.google.common.base.Preconditions;
28
29 public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
30     private static final SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
31
32     // FIXME: is this needed?
33     //    private static final SAXParserFactory saxParserFactory;
34     //    static {
35     //        saxParserFactory = SAXParserFactory.newInstance();
36     //        saxParserFactory.setNamespaceAware(true);
37     //    }
38
39     private final NetconfEXICodec codec;
40
41     public NetconfEXIToMessageDecoder(final NetconfEXICodec codec) {
42         this.codec = Preconditions.checkNotNull(codec);
43     }
44
45     @Override
46     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
47         /*
48          * Note that we could loop here and process all the messages, but we can't do that.
49          * The reason is <stop-exi> operation, which has the contract of immediately stopping
50          * the use of EXI, which means the next message needs to be decoded not by us, but rather
51          * by the XML decoder.
52          */
53         final DOMResult result = new DOMResult();
54         final EXIReader r = codec.getReader();
55
56         final TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler();
57         transformerHandler.setResult(result);
58         r.setContentHandler(transformerHandler);
59
60         try (final InputStream is = new ByteBufInputStream(in)) {
61             r.parse(new InputSource(is));
62         }
63         out.add(new NetconfMessage((Document) result.getNode()));
64     }
65 }