52f93751733b8a7d9c586d443a48f25ba5949967
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / exi / EXISchema.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies s.r.o. 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.netconf.nettyutil.handler.exi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.io.ByteSource;
13 import com.google.common.io.Resources;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import org.opendaylight.netconf.shaded.exificient.core.exceptions.EXIException;
17 import org.opendaylight.netconf.shaded.exificient.core.grammars.Grammars;
18 import org.opendaylight.netconf.shaded.exificient.grammars.GrammarFactory;
19
20 /**
21  * Enumeration of schema modes defined by the NETCONF EXI capability.
22  */
23 public enum EXISchema {
24     NONE("none", GrammarFactory.newInstance().createSchemaLessGrammars()),
25     BUILTIN("builtin", createBuiltinGrammar()),
26     BASE_1_1("base:1.1", createNetconfGrammar());
27
28     private String option;
29     private Grammars grammar;
30
31     EXISchema(final String option, final Grammars grammar) {
32         this.option = requireNonNull(option);
33         this.grammar = requireNonNull(grammar);
34     }
35
36     final String getOption() {
37         return option;
38     }
39
40     final Grammars getGrammar() {
41         return grammar;
42     }
43
44     static EXISchema forOption(final String id) {
45         for (EXISchema s : EXISchema.values()) {
46             if (id.equals(s.getOption())) {
47                 return s;
48             }
49         }
50
51         return null;
52     }
53
54     private static Grammars createNetconfGrammar() {
55         final ByteSource source = Resources.asByteSource(EXISchema.class.getResource("/rfc6241.xsd"));
56         try (InputStream is = source.openStream()) {
57             final Grammars g = GrammarFactory.newInstance().createGrammars(is);
58             g.setSchemaId("base:1.1");
59             return g;
60         } catch (EXIException | IOException e) {
61             throw new IllegalStateException("Failed to create RFC6241 grammar", e);
62         }
63     }
64
65     private static Grammars createBuiltinGrammar() {
66         try {
67             return GrammarFactory.newInstance().createXSDTypesOnlyGrammars();
68         } catch (EXIException e) {
69             throw new IllegalStateException("Failed to create builtin grammar", e);
70         }
71     }
72 }