BUG-472: Add EXI codecs without wiring them
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfEXICodec.java
1 package org.opendaylight.controller.netconf.util.handler;
2
3 import org.openexi.proc.HeaderOptionsOutputType;
4 import org.openexi.proc.common.AlignmentType;
5 import org.openexi.proc.common.EXIOptions;
6 import org.openexi.proc.common.EXIOptionsException;
7 import org.openexi.proc.common.GrammarOptions;
8 import org.openexi.proc.grammars.GrammarCache;
9 import org.openexi.sax.EXIReader;
10 import org.openexi.sax.Transmogrifier;
11
12 import com.google.common.base.Preconditions;
13
14 final class NetconfEXICodec {
15     /**
16      * NETCONF is XML environment, so the use of EXI cookie is not really needed. Adding it
17      * decreases efficiency of encoding by adding human-readable 4 bytes "EXI$" to the head
18      * of the stream. This is really useful, so let's output it now.
19      */
20     private static final boolean OUTPUT_EXI_COOKIE = true;
21     private final AlignmentType alignmentType;
22     private final EXIOptions exiOptions;
23
24     public NetconfEXICodec(final AlignmentType alignmentType, final EXIOptions exiOptions) {
25         this.alignmentType = Preconditions.checkNotNull(alignmentType);
26         this.exiOptions = Preconditions.checkNotNull(exiOptions);
27     }
28
29     private GrammarCache getGrammarCache() {
30         short go = GrammarOptions.DEFAULT_OPTIONS;
31         if (exiOptions.getPreserveComments()) {
32             go = GrammarOptions.addCM(go);
33         }
34         if (exiOptions.getPreserveDTD()) {
35             go = GrammarOptions.addDTD(go);
36         }
37         if (exiOptions.getPreserveNS()) {
38             go = GrammarOptions.addNS(go);
39         }
40         if (exiOptions.getPreservePIs()) {
41             go = GrammarOptions.addPI(go);
42         }
43
44         return new GrammarCache(null, go);
45     }
46
47     EXIReader getReader() throws EXIOptionsException {
48         final EXIReader r = new EXIReader();
49         r.setPreserveLexicalValues(exiOptions.getPreserveLexicalValues());
50         r.setGrammarCache(getGrammarCache());
51         return r;
52     }
53
54     Transmogrifier getTransmogrifier() throws EXIOptionsException {
55         final Transmogrifier transmogrifier = new Transmogrifier();
56         transmogrifier.setAlignmentType(alignmentType);
57         transmogrifier.setBlockSize(exiOptions.getBlockSize());
58         transmogrifier.setGrammarCache(getGrammarCache());
59         transmogrifier.setOutputCookie(OUTPUT_EXI_COOKIE);
60         transmogrifier.setOutputOptions(HeaderOptionsOutputType.all);
61         return transmogrifier;
62     }
63 }