Merge "HostTracker Bundle Separation"
authorGiovanni Meo <gmeo@cisco.com>
Thu, 13 Jun 2013 16:33:55 +0000 (16:33 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 13 Jun 2013 16:33:55 +0000 (16:33 +0000)
57 files changed:
opendaylight/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java
opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-api/src/main/java/org/opendaylight/controller/sal/binding/generator/api/BindingGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/generator/impl/BindingGeneratorImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/BaseYangTypes.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/TypeProviderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentedTypeTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneratedTypesTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-spi/src/main/java/org/opendaylight/controller/sal/binding/generator/spi/TypeProvider.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/AbstractBaseType.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/BindingGeneratorUtil.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/Types.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/ClassCodeGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/Constants.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/GeneratorJavaFile.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/GeneratorUtil.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/InterfaceGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/controller/sal/java/api/generator/test/ClassCodeGeneratorTest.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/controller/sal/java/api/generator/test/GeneratorJavaFileTest.java
opendaylight/sal/yang-prototype/code-generator/maven-sal-api-gen-plugin/src/main/java/org/opendaylight/controller/maven/sal/api/gen/plugin/CodeGeneratorImpl.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/java/org/opendaylight/controller/yang2sources/plugin/it/YangToSourcesPluginTestIT.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/GenerateTest2/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/Util.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/YangToSourcesProcessor.java
opendaylight/sal/yang-prototype/code-generator/samples/maven-code-gen-sample/src/main/yang/controller-network.yang
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/impl/YangParserImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/ParserUtils.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/model/testfile1.yang
opendaylight/sal/yang-prototype/yang/yang-common/src/main/java/org/opendaylight/controller/yang/common/QName.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/ExtendedType.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/SchemaContextUtil.java
opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java
opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/UserManagerImpl.java
opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java

index 0065cb5a08c78488542bb7d065667b0d4f917b38..112725976fa979a3ea2dce55c1f96369709cacc3 100644 (file)
@@ -167,6 +167,314 @@ public class NorthboundIT {
         }
     }
 
+    private void testNodeProperties(JSONObject node, Integer nodeId,
+            String nodeType, Integer timestamp, String timestampName,
+            Integer actionsValue, Integer capabilitiesValue,
+            Integer tablesValue, Integer buffersValue) throws JSONException {
+
+        JSONObject nodeInfo = node.getJSONObject("node");
+        Assert.assertEquals(nodeId, (Integer) nodeInfo.getInt("@id"));
+        Assert.assertEquals(nodeType, nodeInfo.getString("@type"));
+
+        JSONObject properties = node.getJSONObject("properties");
+
+        if (timestamp == null || timestampName == null) {
+            Assert.assertFalse(properties.has("timeStamp"));
+        } else {
+            Assert.assertEquals(
+                    timestamp,
+                    (Integer) properties.getJSONObject("timeStamp").getInt(
+                            "timestamp"));
+            Assert.assertEquals(
+                    timestampName,
+                    properties.getJSONObject("timeStamp").getString(
+                            "timestampName"));
+        }
+        if (actionsValue == null) {
+            Assert.assertFalse(properties.has("actions"));
+        } else {
+            Assert.assertEquals(actionsValue, (Integer) properties
+                    .getJSONObject("actions").getInt("actionsValue"));
+        }
+        if (capabilitiesValue == null) {
+            Assert.assertFalse(properties.has("capabilities"));
+        } else {
+            Assert.assertEquals(capabilitiesValue, (Integer) properties
+                    .getJSONObject("capabilities").getInt("capabilitiesValue"));
+        }
+        if (tablesValue == null) {
+            Assert.assertFalse(properties.has("tables"));
+        } else {
+            Assert.assertEquals(tablesValue, (Integer) properties
+                    .getJSONObject("tables").getInt("tablesValue"));
+        }
+        if (buffersValue == null) {
+            Assert.assertFalse(properties.has("buffers"));
+        } else {
+            Assert.assertEquals(buffersValue, (Integer) properties
+                    .getJSONObject("buffers").getInt("buffersValue"));
+        }
+    }
+
+    private void testNodeConnectorProperties(
+            JSONObject nodeConnectorProperties, Integer ncId, String ncType,
+            Integer nodeId, String nodeType, Integer state,
+            Integer capabilities, Integer bandwidth) throws JSONException {
+
+        JSONObject nodeConnector = nodeConnectorProperties
+                .getJSONObject("nodeconnector");
+        JSONObject node = nodeConnector.getJSONObject("node");
+        JSONObject properties = nodeConnectorProperties
+                .getJSONObject("properties");
+
+        Assert.assertEquals(ncId, (Integer) nodeConnector.getInt("@id"));
+        Assert.assertEquals(ncType, nodeConnector.getString("@type"));
+        Assert.assertEquals(nodeId, (Integer) node.getInt("@id"));
+        Assert.assertEquals(nodeType, node.getString("@type"));
+        if (state == null) {
+            Assert.assertFalse(properties.has("state"));
+        } else {
+            Assert.assertEquals(
+                    state,
+                    (Integer) properties.getJSONObject("state").getInt(
+                            "stateValue"));
+        }
+        if (capabilities == null) {
+            Assert.assertFalse(properties.has("capabilities"));
+        } else {
+            Assert.assertEquals(capabilities, (Integer) properties
+                    .getJSONObject("capabilities").getInt("capabilitiesValue"));
+        }
+        if (bandwidth == null) {
+            Assert.assertFalse(properties.has("bandwidth"));
+        } else {
+            Assert.assertEquals(
+                    bandwidth,
+                    (Integer) properties.getJSONObject("bandwidth").getInt(
+                            "bandwidthValue"));
+        }
+
+    }
+
+    @Test
+    public void testSwitchManager() {
+        String baseURL = "http://127.0.0.1:8080/controller/nb/v2/switch/default/";
+
+        // define Node/NodeConnector attributes for test
+        int nodeId_1 = 51966;
+        int nodeId_2 = 3366;
+        int nodeId_3 = 4477;
+        int nodeConnectorId_1 = 51966;
+        int nodeConnectorId_2 = 12;
+        int nodeConnectorId_3 = 34;
+        String nodeType = "STUB";
+        String ncType = "STUB";
+        int timestamp_1 = 100000;
+        String timestampName_1 = "connectedSince";
+        int actionsValue_1 = 2;
+        int capabilitiesValue_1 = 3;
+        int tablesValue_1 = 1;
+        int buffersValue_1 = 1;
+        int ncState = 1;
+        int ncCapabilities = 1;
+        int ncBandwidth = 1000000000;
+
+        // Test GET all nodes
+        try {
+            String result = getJsonResult(baseURL + "nodes");
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+
+            // Test for first node
+            JSONObject node = getJsonInstance(json, "nodeProperties", nodeId_1);
+            Assert.assertNotNull(node);
+            testNodeProperties(node, nodeId_1, nodeType, timestamp_1,
+                    timestampName_1, actionsValue_1, capabilitiesValue_1,
+                    tablesValue_1, buffersValue_1);
+
+            // Test 2nd node, properties of 2nd node same as first node
+            node = getJsonInstance(json, "nodeProperties", nodeId_2);
+            Assert.assertNotNull(node);
+            testNodeProperties(node, nodeId_2, nodeType, timestamp_1,
+                    timestampName_1, actionsValue_1, capabilitiesValue_1,
+                    tablesValue_1, buffersValue_1);
+
+            // Test 3rd node, properties of 3rd node same as first node
+            node = getJsonInstance(json, "nodeProperties", nodeId_3);
+            Assert.assertNotNull(node);
+            testNodeProperties(node, nodeId_3, nodeType, timestamp_1,
+                    timestampName_1, actionsValue_1, capabilitiesValue_1,
+                    tablesValue_1, buffersValue_1);
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+
+        // Test GET nodeConnectors of a node
+        try {
+            //Test first node
+            String result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+            JSONObject nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_1, ncType, nodeId_1, nodeType, ncState,
+                    ncCapabilities, ncBandwidth);
+
+            //Test second node
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_2);
+            jt = new JSONTokener(result);
+            json = new JSONObject(jt);
+            nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_2, ncType, nodeId_2, nodeType, ncState,
+                    ncCapabilities, ncBandwidth);
+
+            //Test third node
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_3);
+            jt = new JSONTokener(result);
+            json = new JSONObject(jt);
+
+            nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_3, ncType, nodeId_3, nodeType, ncState,
+                    ncCapabilities, ncBandwidth);
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+
+        // Test delete node property
+        try {
+            // Delete timestamp property from node1
+            String result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                    + "/property/timeStamp", "DELETE");
+            Assert.assertEquals(200, httpResponseCode.intValue());
+
+            // Check node1
+            result = getJsonResult(baseURL + "nodes");
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+            JSONObject node = getJsonInstance(json, "nodeProperties", nodeId_1);
+            Assert.assertNotNull(node);
+            testNodeProperties(node, nodeId_1, nodeType, null, null,
+                    actionsValue_1, capabilitiesValue_1, tablesValue_1,
+                    buffersValue_1);
+
+            // Delete actions property from node2
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_2
+                    + "/property/actions", "DELETE");
+            Assert.assertEquals(200, httpResponseCode.intValue());
+
+            // Check node2
+            result = getJsonResult(baseURL + "nodes");
+            jt = new JSONTokener(result);
+            json = new JSONObject(jt);
+            node = getJsonInstance(json, "nodeProperties", nodeId_2);
+            Assert.assertNotNull(node);
+            testNodeProperties(node, nodeId_2, nodeType, timestamp_1,
+                    timestampName_1, null, capabilitiesValue_1, tablesValue_1,
+                    buffersValue_1);
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+
+        // Test add property to node
+        try {
+            // Add Tier and Bandwidth property to node1
+            String result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                    + "/property/tier/1001", "PUT");
+            Assert.assertEquals(201, httpResponseCode.intValue());
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                    + "/property/bandwidth/1002", "PUT");
+            Assert.assertEquals(201, httpResponseCode.intValue());
+
+            // Test for first node
+            result = getJsonResult(baseURL + "nodes");
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+            JSONObject node = getJsonInstance(json, "nodeProperties", nodeId_1);
+            Assert.assertNotNull(node);
+            Assert.assertEquals(1001, node.getJSONObject("properties")
+                    .getJSONObject("tier").getInt("tierValue"));
+            Assert.assertEquals(1002, node.getJSONObject("properties")
+                    .getJSONObject("bandwidth").getInt("bandwidthValue"));
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+
+        // Test delete nodeConnector property
+        try {
+            // Delete state property of nodeconnector1
+            String result = getJsonResult(baseURL + "nodeconnector/STUB/"
+                    + nodeId_1 + "/STUB/" + nodeConnectorId_1
+                    + "/property/state", "DELETE");
+            Assert.assertEquals(200, httpResponseCode.intValue());
+
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+            JSONObject nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_1, ncType, nodeId_1, nodeType, null,
+                    ncCapabilities, ncBandwidth);
+
+            // Delete capabilities property of nodeconnector2
+            result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_2
+                    + "/STUB/" + nodeConnectorId_2 + "/property/capabilities",
+                    "DELETE");
+            Assert.assertEquals(200, httpResponseCode.intValue());
+
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_2);
+            jt = new JSONTokener(result);
+            json = new JSONObject(jt);
+            nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_2, ncType, nodeId_2, nodeType, ncState,
+                    null, ncBandwidth);
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+
+        // Test PUT nodeConnector property
+        try {
+            int newBandwidth = 1001;
+
+            // Add Name/Bandwidth property to nodeConnector1
+            String result = getJsonResult(baseURL + "nodeconnector/STUB/"
+                    + nodeId_1 + "/STUB/" + nodeConnectorId_1
+                    + "/property/bandwidth/" + newBandwidth, "PUT");
+            Assert.assertEquals(201, httpResponseCode.intValue());
+
+            result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+            JSONTokener jt = new JSONTokener(result);
+            JSONObject json = new JSONObject(jt);
+            JSONObject nodeConnectorProperties = json
+                    .getJSONObject("nodeConnectorProperties");
+
+            // Check for new bandwidth value, state value removed from previous
+            // test
+            testNodeConnectorProperties(nodeConnectorProperties,
+                    nodeConnectorId_1, ncType, nodeId_1, nodeType, null,
+                    ncCapabilities, newBandwidth);
+
+        } catch (Exception e) {
+            Assert.assertTrue(false);
+        }
+    }
+
     @Test
     public void testStatistics() {
         String actionTypes[] = { "drop", "loopback", "flood", "floodAll",
index e92583a33a9543c30c60b269ddc67a0c075c8561..d3b023512bebd5790559b7e047b813e0558395e9 100644 (file)
@@ -205,7 +205,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         Property prop = switchManager.createProperty(propName, propValue);
         if (prop == null) {
@@ -262,8 +262,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
-
+        Node node = Node.fromString(nodeType, nodeId);
         Status ret = switchManager.removeNodeProp(node, propertyName);
         if (ret.isSuccess()) {
             return Response.ok().build();
@@ -316,8 +315,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
-
+        Node node = Node.fromString(nodeType, nodeId);
         List<NodeConnectorProperties> res = new ArrayList<NodeConnectorProperties>();
         Set<NodeConnector> ncs = switchManager.getNodeConnectors(node);
         if (ncs == null) {
@@ -397,12 +395,12 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
                 nodeConnectorId);
         NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorId, node);
+                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
 
         Property prop = switchManager.createProperty(propName, propValue);
         if (prop == null) {
@@ -470,13 +468,12 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
                 nodeConnectorId);
         NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorId, node);
-
+                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
         Status ret = switchManager.removeNodeConnectorProp(nc, propertyName);
         if (ret.isSuccess()) {
             return Response.ok().build();
index b3909a775bbe36156fa127e9b54841f02556a40e..22a4343f332ed2e79e7f7ecc979d8535acc4ea26 100644 (file)
@@ -42,9 +42,19 @@ public class InventoryService implements IPluginInInventoryService {
     private static final Logger logger = LoggerFactory
             .getLogger(InventoryService.class);
 
-    private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties are maintained in global container only
-    private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties are maintained in global container only
-
+    private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties
+                                                                  // are
+                                                                  // maintained
+                                                                  // in global
+                                                                  // container
+                                                                  // only
+    private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties
+                                                                                    // are
+                                                                                    // maintained
+                                                                                    // in
+                                                                                    // global
+                                                                                    // container
+                                                                                    // only
 
     /**
      * Function called by the dependency manager when all the required
@@ -55,51 +65,65 @@ public class InventoryService implements IPluginInInventoryService {
         nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
         nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
         Node.NodeIDType.registerIDType("STUB", Integer.class);
-        NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class, "STUB");
-    }
+        NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class,
+                "STUB");
 
-    /**
-     * Function called by the dependency manager when at least one dependency
-     * become unsatisfied or when the component is shutting down because for
-     * example bundle is being stopped.
-     *
-     */
-    void destroy() {
+        setupNodeProps();
+        setupNodeConnectorProps();
     }
 
-    /**
-     * Function called by dependency manager after "init ()" is called and after
-     * the services provided by the class are registered in the service registry
-     *
-     */
-    void start() {
-    }
+    private void setupNodeConnectorProps() {
+        Map<String, Property> ncPropMap = new HashMap<String, Property>();
+        Capabilities cap = new Capabilities(
+                CapabilitiesType.FLOW_STATS_CAPABILITY.getValue());
+        ncPropMap.put(Capabilities.CapabilitiesPropName, cap);
+        Bandwidth bw = new Bandwidth(Bandwidth.BW1Gbps);
+        ncPropMap.put(Bandwidth.BandwidthPropName, bw);
+        State st = new State(State.EDGE_UP);
+        ncPropMap.put(State.StatePropName, st);
 
-    /**
-     * Function called by the dependency manager before the services exported by
-     * the component are unregistered, this will be followed by a "destroy ()"
-     * calls
-     *
-     */
-    void stop() {
-    }
+        // setup property map for all node connectors
+        NodeConnector nc;
+        Node node;
+        try {
+            node = new Node("STUB", new Integer(0xCAFE));
+            nc = new NodeConnector("STUB", 0xCAFE, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
 
-    /**
-     * Retrieve nodes from openflow
-     */
-    @Override
-    public ConcurrentMap<Node, Map<String, Property>> getNodeProps() {
+        try {
+            node = new Node("STUB", 3366);
+            nc = new NodeConnector("STUB", 12, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
+
+        try {
+            node = new Node("STUB", 4477);
+            nc = new NodeConnector("STUB", 34, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
 
-        //  setup nodeProps
+    }
+
+    private void setupNodeProps() {
         Map<String, Property> propMap = new HashMap<String, Property>();
 
-        Tables t = new Tables((byte)1);
+        Tables t = new Tables((byte) 1);
         propMap.put(Tables.TablesPropName, t);
-        Capabilities c = new Capabilities((int)3);
+        Capabilities c = new Capabilities((int) 3);
         propMap.put(Capabilities.CapabilitiesPropName, c);
-        Actions a = new Actions((int)2);
+        Actions a = new Actions((int) 2);
         propMap.put(Actions.ActionsPropName, a);
-        Buffers b = new Buffers((int)1);
+        Buffers b = new Buffers((int) 1);
         propMap.put(Buffers.BuffersPropName, b);
         Long connectedSinceTime = 100000L;
         TimeStamp timeStamp = new TimeStamp(connectedSinceTime,
@@ -108,28 +132,61 @@ public class InventoryService implements IPluginInInventoryService {
 
         // setup property map for all nodes
         Node node;
-        try{
+        try {
             node = new Node("STUB", new Integer(0xCAFE));
-        }catch(ConstructionException e){
+        } catch (ConstructionException e) {
             node = null;
         }
 
         nodeProps.put(node, propMap);
 
-        try{
+        try {
             node = new Node("STUB", 3366);
-        }catch(ConstructionException e){
+        } catch (ConstructionException e) {
             node = null;
         }
         nodeProps.put(node, propMap);
 
-        try{
+        try {
             node = new Node("STUB", 4477);
-        }catch(ConstructionException e){
+        } catch (ConstructionException e) {
             node = null;
         }
         nodeProps.put(node, propMap);
 
+    }
+
+    /**
+     * Function called by the dependency manager when at least one dependency
+     * become unsatisfied or when the component is shutting down because for
+     * example bundle is being stopped.
+     *
+     */
+    void destroy() {
+    }
+
+    /**
+     * Function called by dependency manager after "init ()" is called and after
+     * the services provided by the class are registered in the service registry
+     *
+     */
+    void start() {
+    }
+
+    /**
+     * Function called by the dependency manager before the services exported by
+     * the component are unregistered, this will be followed by a "destroy ()"
+     * calls
+     *
+     */
+    void stop() {
+    }
+
+    /**
+     * Retrieve nodes from openflow
+     */
+    @Override
+    public ConcurrentMap<Node, Map<String, Property>> getNodeProps() {
         return nodeProps;
     }
 
@@ -139,49 +196,7 @@ public class InventoryService implements IPluginInInventoryService {
     @Override
     public ConcurrentMap<NodeConnector, Map<String, Property>> getNodeConnectorProps(
             Boolean refresh) {
-
-        //  setup nodeConnectorProps
-        Map<String, Property> ncPropMap = new HashMap<String, Property>();
-        Capabilities cap = new Capabilities
-                (CapabilitiesType.FLOW_STATS_CAPABILITY.getValue());
-        ncPropMap.put(Capabilities.CapabilitiesPropName, cap);
-        Bandwidth bw = new Bandwidth (Bandwidth.BW1Gbps);
-        ncPropMap.put(Bandwidth.BandwidthPropName, bw);
-        State st = new State (State.EDGE_UP);
-        ncPropMap.put(State.StatePropName, st);
-
-        // setup property map for all node connectors
-        NodeConnector nc;
-        Node node;
-        try{
-            node = new Node("STUB", new Integer(0xCAFE));
-            nc = new NodeConnector("STUB", 0xCAFE, node);
-        }catch(ConstructionException e){
-            nc = null;
-            node = null;
-        }
-        nodeConnectorProps.put(nc, ncPropMap);
-
-        try{
-            node = new Node("STUB", 3366);
-            nc = new NodeConnector("STUB", 12, node);
-         } catch(ConstructionException e){
-            nc = null;
-            node = null;
-         }
-         nodeConnectorProps.put(nc, ncPropMap);
-
-         try{
-            node = new Node("STUB", 4477);
-            nc = new NodeConnector("STUB", 34, node);
-         }catch(ConstructionException e){
-            nc = null;
-            node = null;
-         }
-         nodeConnectorProps.put(nc, ncPropMap);
-
-         return nodeConnectorProps;
+        return nodeConnectorProps;
     }
 
-
 }
index 29d1c71204a68bde4edb0d66936b121590551ac2..a9eefd3a8a689d8b4d92bd76fc4ec0edf1198193 100644 (file)
@@ -46,7 +46,6 @@ import org.slf4j.LoggerFactory;
 
 public class DataPacketService implements IPluginOutDataPacketService,
         IDataPacketService {
-    private int RXMAXQUEUESIZE = 1000;
     private int TXMAXQUEUESIZE = 1000;
     protected static final Logger logger = LoggerFactory
             .getLogger(DataPacketService.class);
@@ -63,31 +62,21 @@ public class DataPacketService implements IPluginOutDataPacketService,
         pluginInDataService =
         new ConcurrentHashMap<String, IPluginInDataPacketService>();
     private Map<String, AtomicInteger> statistics = new HashMap<String, AtomicInteger>();
-    /**
-     * Queue for packets received from Data Path
-     */
-    private LinkedBlockingQueue<RawPacket> rxQueue = new LinkedBlockingQueue<RawPacket>(
-            RXMAXQUEUESIZE);
+
     /**
      * Queue for packets that need to be transmitted to Data Path
      */
     private LinkedBlockingQueue<RawPacket> txQueue = new LinkedBlockingQueue<RawPacket>(
-            RXMAXQUEUESIZE);
+            TXMAXQUEUESIZE);
     /**
      * Transmission thread
      */
     private Thread txThread = new Thread(new TxLoop(),
             "DataPacketService TX thread");
-    /**
-     * Receiving thread
-     */
-    private Thread rxThread = new Thread(new RxLoop(),
-            "DataPacketService RX thread");
 
     /**
      * Representation of a Data Packet Listener including of its
      * properties
-     *
      */
     private class DataPacketListener {
         // Key fields
@@ -152,49 +141,30 @@ public class DataPacketService implements IPluginOutDataPacketService,
 
     /**
      * Loop for processing Received packets
-     *
      */
-    private class RxLoop implements Runnable {
-        public void run() {
-            RawPacket pkt;
-            try {
-                for (pkt = rxQueue.take(); pkt != null; pkt = rxQueue.take()) {
-                    for (List<DataPacketListener> serialListeners : listenDataPacket) {
-                        int i = 0;
-                        for (i = 0; i < serialListeners.size(); i++) {
-                            RawPacket copyPkt = null;
-                            try {
-                                copyPkt = new RawPacket(pkt);
-                            } catch (ConstructionException cex) {
-                                logger.debug("Error while cloning the packet");
-                            }
-                            if (copyPkt == null) {
-                                increaseStat("RXPacketCopyFailed");
-                                continue;
-                            }
-                            DataPacketListener l = serialListeners.get(i);
-                            IListenDataPacket s = (l == null ? null
-                                    : l.listener);
-                            if (s != null) {
-                                try {
-                                    // TODO Make sure to filter based
-                                    // on the match too, later on
-                                    PacketResult res = s
-                                            .receiveDataPacket(copyPkt);
-                                    increaseStat("RXPacketSuccess");
-                                    if (res.equals(PacketResult.CONSUME)) {
-                                        increaseStat("RXPacketSerialExit");
-                                        break;
-                                    }
-                                } catch (Exception e) {
-                                    increaseStat("RXPacketFailedForException");
-                                }
-                            }
+    private void dispatchPacket(RawPacket pkt) {
+
+        // for now we treat all listeners as serial listeners
+        for (List<DataPacketListener> serialListeners : listenDataPacket) {
+            for (DataPacketListener l : serialListeners) {
+
+                // TODO: possibly deal with read-only and read-write packet
+                // copies
+                IListenDataPacket s = (l == null ? null : l.listener);
+                if (s != null) {
+                    try {
+                        // TODO Make sure to filter based on the match too,
+                        // later on
+                        PacketResult res = s.receiveDataPacket(pkt);
+                        increaseStat("RXPacketSuccess");
+                        if (res.equals(PacketResult.CONSUME)) {
+                            increaseStat("RXPacketSerialExit");
+                            break;
                         }
+                    } catch (Exception e) {
+                        increaseStat("RXPacketFailedForException");
                     }
                 }
-            } catch (InterruptedException e) {
-                // Not a big deal
             }
         }
     }
@@ -431,7 +401,6 @@ public class DataPacketService implements IPluginOutDataPacketService,
      */
     void init() {
         this.txThread.start();
-        this.rxThread.start();
     }
 
     /**
@@ -447,14 +416,11 @@ public class DataPacketService implements IPluginOutDataPacketService,
         this.indexDataPacket.clear();
         this.pluginInDataService.clear();
         this.statistics.clear();
-        this.rxQueue.clear();
         this.txQueue.clear();
         this.txThread.interrupt();
-        this.rxThread.interrupt();
         // Wait for them to be done
         try {
             this.txThread.join();
-            this.rxThread.join();
         } catch (InterruptedException ex) {
             // Not a big deal
         }
@@ -484,12 +450,8 @@ public class DataPacketService implements IPluginOutDataPacketService,
             return PacketResult.IGNORED;
         }
 
-        // If the queue was full don't wait, rather increase a counter
-        // for it
-        if (!this.rxQueue.offer(inPkt)) {
-            increaseStat("fullRXQueue");
-            return PacketResult.IGNORED;
-        }
+        // send the packet off to be processed by listeners
+        this.dispatchPacket(inPkt);
 
         // Walk the chain of listener going first throw all the
         // parallel ones and for each parallel in serial
index bed7989074c7da7cff666b55d4afbb54f620e910..a9859f76304a6c4953bf7e17adb4619f5164ece8 100644 (file)
@@ -7,13 +7,47 @@
  */\r
 package org.opendaylight.controller.sal.binding.generator.api;\r
 \r
-import java.util.List;\r
-\r
 import org.opendaylight.controller.sal.binding.model.api.Type;\r
+import org.opendaylight.controller.yang.model.api.Module;\r
 import org.opendaylight.controller.yang.model.api.SchemaContext;\r
 \r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+/**\r
+ *\r
+ *\r
+ */\r
 public interface BindingGenerator {\r
 \r
+    /**\r
+     * Generate Types from whole Schema Context.\r
+     * <br>\r
+     * The method will return List of All Generated Types that could be\r
+     * Generated from Schema Context.\r
+     *\r
+     *\r
+     * @param context Schema Context\r
+     * @return List of Generated Types\r
+     *\r
+     * @see SchemaContext\r
+     */\r
     public List<Type> generateTypes(final SchemaContext context);\r
 \r
+    /**\r
+     * Generate Types from Schema Context restricted by sub set of specified\r
+     * Modules. The Schema Context MUST contain all of the sub modules\r
+     * otherwise the there is no guarantee that result List of Generated\r
+     * Types will contain correct Generated Types.\r
+     *\r
+     * @param context Schema Context\r
+     * @param modules Sub Set of Modules\r
+     * @return List of Generated Types restricted by sub set of Modules\r
+     *\r
+     * @see Module\r
+     * @see SchemaContext\r
+     *\r
+     */\r
+    public List<Type> generateTypes(final SchemaContext context,\r
+                                    final Set<Module> modules);\r
 }\r
index a903ef15811daeb7197c4ef7a80ca612c30520e4..65d4b48dbe57b1a9b2b27f6b83b7cfdc507011b8 100644 (file)
@@ -12,9 +12,7 @@ import org.opendaylight.controller.binding.generator.util.Types;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.spi.TypeProvider;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.*;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
 import org.opendaylight.controller.sal.binding.yang.types.TypeProviderImpl;
 import org.opendaylight.controller.yang.common.QName;
@@ -30,7 +28,7 @@ import static org.opendaylight.controller.binding.generator.util.BindingGenerato
 import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.findParentModule;
 
-public class BindingGeneratorImpl implements BindingGenerator {
+public final class BindingGeneratorImpl implements BindingGenerator {
 
     private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
     private TypeProvider typeProvider;
@@ -43,69 +41,177 @@ public class BindingGeneratorImpl implements BindingGenerator {
     @Override
     public List<Type> generateTypes(final SchemaContext context) {
         if (context == null) {
-            throw new IllegalArgumentException("Schema Context reference cannot be NULL");
+            throw new IllegalArgumentException("Schema Context reference " +
+                    "cannot be NULL!");
         }
         if (context.getModules() == null) {
-            throw new IllegalStateException("Schema Context does not contain defined modules!");
+            throw new IllegalStateException("Schema Context does not contain " +
+                    "defined modules!");
         }
 
-        final List<Type> genTypes = new ArrayList<>();
+        final List<Type> generatedTypes = new ArrayList<>();
         schemaContext = context;
         typeProvider = new TypeProviderImpl(context);
         final Set<Module> modules = context.getModules();
         genTypeBuilders = new HashMap<>();
         for (final Module module : modules) {
-            final DataNodeIterator moduleIterator = new DataNodeIterator(
-                    module);
-
-            final List<AugmentationSchema> sortedAugmentations = provideSortedAugmentations(module);
-            final List<ContainerSchemaNode> schemaContainers = moduleIterator
-                    .allContainers();
-            final List<ListSchemaNode> schemaLists = moduleIterator
-                    .allLists();
-
-            final String basePackageName = moduleNamespaceToPackageName(module);
-            if ((schemaContainers != null)
-                    && !schemaContainers.isEmpty()) {
-                for (final ContainerSchemaNode container : schemaContainers) {
-                    genTypes.add(containerToGenType(basePackageName,
-                            container));
-                }
-            }
-            if ((schemaLists != null) && !schemaLists.isEmpty()) {
-                for (final ListSchemaNode list : schemaLists) {
-                    genTypes.addAll(listToGenType(basePackageName, list));
-                }
+            generatedTypes.add(moduleToDataType(module));
+            generatedTypes.addAll(allTypeDefinitionsToGenTypes(module));
+            generatedTypes.addAll(allContainersToGenTypes(module));
+            generatedTypes.addAll(allListsToGenTypes(module));
+            generatedTypes.addAll(allAugmentsToGenTypes(module));
+            generatedTypes.addAll(allRPCMethodsToGenType(module));
+            generatedTypes.addAll(allNotifycationsToGenType(module));
+        }
+        return generatedTypes;
+    }
+
+    @Override
+    public List<Type> generateTypes(final SchemaContext context,
+                                    final Set<Module> modules) {
+        if (context == null) {
+            throw new IllegalArgumentException("Schema Context reference " +
+                    "cannot be NULL!");
+        }
+        if (context.getModules() == null) {
+            throw new IllegalStateException("Schema Context does not contain " +
+                    "defined modules!");
+        }
+        if (modules == null) {
+            throw new IllegalArgumentException("Sef of Modules cannot be " +
+                    "NULL!");
+        }
+
+        final List<Type> filteredGenTypes = new ArrayList<>();
+        schemaContext = context;
+        typeProvider = new TypeProviderImpl(context);
+        final Set<Module> contextModules = context.getModules();
+        genTypeBuilders = new HashMap<>();
+        for (final Module contextModule : contextModules) {
+            final List<Type> generatedTypes = new ArrayList<>();
+
+            generatedTypes.add(moduleToDataType(contextModule));
+            generatedTypes.addAll(allTypeDefinitionsToGenTypes(contextModule));
+            generatedTypes.addAll(allContainersToGenTypes(contextModule));
+            generatedTypes.addAll(allListsToGenTypes(contextModule));
+            generatedTypes.addAll(allAugmentsToGenTypes(contextModule));
+            generatedTypes.addAll(allRPCMethodsToGenType(contextModule));
+            generatedTypes.addAll(allNotifycationsToGenType(contextModule));
+
+            if (modules.contains(contextModule)) {
+                filteredGenTypes.addAll(generatedTypes);
             }
+        }
+        return filteredGenTypes;
+    }
+
+    private List<Type> allTypeDefinitionsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+        if (module.getTypeDefinitions() == null) {
+            throw new IllegalArgumentException("Type Definitions for module " +
+                    module.getName() + " cannot be NULL!");
+        }
 
-            if ((sortedAugmentations != null)
-                    && !sortedAugmentations.isEmpty()) {
-                for (final AugmentationSchema augment : sortedAugmentations) {
-                    genTypes.addAll(augmentationToGenTypes(basePackageName, augment));
+        final Set<TypeDefinition<?>> typeDefinitions = module
+                .getTypeDefinitions();
+        final List<Type> generatedTypes = new ArrayList<>();
+        for (final TypeDefinition<?> typedef : typeDefinitions) {
+            if (typedef != null) {
+                final Type type = ((TypeProviderImpl)typeProvider)
+                        .generatedTypeForExtendedDefinitionType(typedef);
+                if ((type != null) && !generatedTypes.contains(type)) {
+                    generatedTypes.add(type);
                 }
             }
+        }
+        return generatedTypes;
+    }
 
-            final GeneratedType genDataType = moduleToDataType(basePackageName, module);
-            final List<GeneratedType> genRpcType = rpcMethodsToGenType(basePackageName, module);
-            final List<Type> genNotifyType = notifycationsToGenType(basePackageName, module);
+    private List<Type> allContainersToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
 
-            if (genDataType != null) {
-                genTypes.add(genDataType);
-            }
-            if (genRpcType != null) {
-                genTypes.addAll(genRpcType);
-            }
-            if (genNotifyType != null) {
-                genTypes.addAll(genNotifyType);
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of Child " +
+                    "Nodes in module " + module.getName() + " cannot be " +
+                    "NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final DataNodeIterator it = new DataNodeIterator(
+                module);
+        final List<ContainerSchemaNode> schemaContainers = it.allContainers();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        for (final ContainerSchemaNode container : schemaContainers) {
+            generatedTypes.add(containerToGenType(basePackageName,
+                    container));
+        }
+        return generatedTypes;
+    }
+
+    private List<Type> allListsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of Child " +
+                    "Nodes in module " + module.getName() + " cannot be " +
+                    "NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final DataNodeIterator it = new DataNodeIterator(
+                module);
+        final List<ListSchemaNode> schemaLists = it.allLists();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        if (schemaLists != null) {
+            for (final ListSchemaNode list : schemaLists) {
+                generatedTypes.addAll(listToGenType(basePackageName, list));
             }
         }
-        genTypes.addAll(((TypeProviderImpl) typeProvider)
-                .getGeneratedTypeDefs());
+        return generatedTypes;
+    }
 
-        return genTypes;
+    private List<Type> allAugmentsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of " +
+                    "Augmentation Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final List<AugmentationSchema> augmentations = resolveAugmentations(module);
+        for (final AugmentationSchema augment : augmentations) {
+            generatedTypes.addAll(augmentationToGenTypes(basePackageName, augment));
+        }
+        return generatedTypes;
     }
 
-    private List<AugmentationSchema> provideSortedAugmentations(final Module module) {
+    private List<AugmentationSchema> resolveAugmentations(final Module module) {
         if (module == null) {
             throw new IllegalArgumentException("Module reference cannot be NULL!");
         }
@@ -142,7 +248,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return sortedAugmentations;
     }
 
-    private GeneratedType moduleToDataType(final String basePackageName, final Module module) {
+    private GeneratedType moduleToDataType(final Module module) {
         if (module == null) {
             throw new IllegalArgumentException("Module reference cannot be NULL!");
         }
@@ -150,6 +256,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(
                 module, "Data");
 
+        final String basePackageName = moduleNamespaceToPackageName(module);
         if (moduleDataTypeBuilder != null) {
             final Set<DataSchemaNode> dataNodes = module.getChildNodes();
             resolveDataSchemaNodes(basePackageName, moduleDataTypeBuilder, dataNodes);
@@ -157,17 +264,91 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return moduleDataTypeBuilder.toInstance();
     }
 
-    private boolean isDerivedFromEnumerationType(
-            final TypeDefinition<?> typeDefinition) {
-        if (typeDefinition != null) {
-            if (typeDefinition.getBaseType() instanceof EnumTypeDefinition) {
-                return true;
-            } else if (typeDefinition.getBaseType() instanceof ExtendedType) {
-                return isDerivedFromEnumerationType(typeDefinition
-                        .getBaseType());
+    private List<GeneratedType> allRPCMethodsToGenType(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of " +
+                    "RPC Method Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
+        final List<GeneratedType> genRPCTypes = new ArrayList<>();
+
+        for (final RpcDefinition rpc : rpcDefinitions) {
+            if (rpc != null) {
+                final List<DataNodeIterator> rpcInOut = new ArrayList<>();
+                rpcInOut.add(new DataNodeIterator(rpc.getInput()));
+                rpcInOut.add(new DataNodeIterator(rpc.getOutput()));
+
+                for (DataNodeIterator it : rpcInOut) {
+                    List<ContainerSchemaNode> nContainers = it.allContainers();
+                    if ((nContainers != null) && !nContainers.isEmpty()) {
+                        for (final ContainerSchemaNode container : nContainers) {
+                            genRPCTypes.add(containerToGenType(basePackageName, container));
+                        }
+                    }
+                }
             }
         }
-        return false;
+        return genRPCTypes;
+    }
+
+    private List<Type> allNotifycationsToGenType(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException("Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of " +
+                    "Notification Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final List<Type> genNotifyTypes = new ArrayList<>();
+        final Set<NotificationDefinition> notifications = module
+                .getNotifications();
+
+        for (final NotificationDefinition notification : notifications) {
+            if (notification != null) {
+                final List<DataNodeIterator> notifyChildren = new ArrayList<>();
+
+                for (DataSchemaNode childNode : notification.getChildNodes()) {
+                    if (childNode instanceof DataNodeContainer) {
+                        notifyChildren.add(new DataNodeIterator((DataNodeContainer) childNode));
+                    }
+                }
+
+                for (DataNodeIterator it : notifyChildren) {
+                    List<ContainerSchemaNode> nContainers = it.allContainers();
+                    List<ListSchemaNode> nLists = it.allLists();
+                    if ((nContainers != null) && !nContainers.isEmpty()) {
+                        for (final ContainerSchemaNode container : nContainers) {
+                            genNotifyTypes.add(containerToGenType(basePackageName, container));
+                        }
+                    }
+                    if ((nLists != null) && !nLists.isEmpty()) {
+                        for (final ListSchemaNode list : nLists) {
+                            genNotifyTypes.addAll(listToGenType(basePackageName, list));
+                        }
+                    }
+                }
+            }
+        }
+        return genNotifyTypes;
     }
 
     private EnumTypeDefinition enumTypeDefFromExtendedType(
@@ -182,7 +363,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return null;
     }
 
-    private EnumBuilder resolveEnumFromTypeDefinition(
+    private EnumBuilder resolveInnerEnumFromTypeDefinition(
             final EnumTypeDefinition enumTypeDef, final String enumName,
             final GeneratedTypeBuilder typeBuilder) {
         if ((enumTypeDef != null) && (typeBuilder != null)
@@ -230,75 +411,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
     }
 
-    private List<GeneratedType> rpcMethodsToGenType(final String basePackageName, final Module module) {
-        if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
-        }
-
-        final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
-        final List<GeneratedType> rpcTypes = new ArrayList<>();
-
-        if ((rpcDefinitions != null) && !rpcDefinitions.isEmpty()) {
-            for (final RpcDefinition rpc : rpcDefinitions) {
-                if (rpc != null) {
-                    final List<DataNodeIterator> rpcInOut = new ArrayList<>();
-                    rpcInOut.add(new DataNodeIterator(rpc.getInput()));
-                    rpcInOut.add(new DataNodeIterator(rpc.getOutput()));
-
-                    for (DataNodeIterator it : rpcInOut) {
-                        List<ContainerSchemaNode> nContainers = it.allContainers();
-                        if ((nContainers != null) && !nContainers.isEmpty()) {
-                            for (final ContainerSchemaNode container : nContainers) {
-                                rpcTypes.add(containerToGenType(basePackageName, container));
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        return rpcTypes;
-    }
-
-    private List<Type> notifycationsToGenType(final String basePackageName, final Module module) {
-        if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
-        }
-        final List<Type> notificationTypes = new ArrayList<>();
-        final Set<NotificationDefinition> notifications = module
-                .getNotifications();
-
-        if ((notifications != null) && !notifications.isEmpty()) {
-            for (final NotificationDefinition notification : notifications) {
-                if (notification != null) {
-                    final List<DataNodeIterator> notifyChildren = new ArrayList<>();
-
-                    for (DataSchemaNode childNode : notification.getChildNodes()) {
-                        if (childNode instanceof DataNodeContainer) {
-                            notifyChildren.add(new DataNodeIterator((DataNodeContainer) childNode));
-                        }
-                    }
-
-                    for (DataNodeIterator it : notifyChildren) {
-                        List<ContainerSchemaNode> nContainers = it.allContainers();
-                        List<ListSchemaNode> nLists = it.allLists();
-                        if ((nContainers != null) && !nContainers.isEmpty()) {
-                            for (final ContainerSchemaNode container : nContainers) {
-                                notificationTypes.add(containerToGenType(basePackageName, container));
-                            }
-                        }
-                        if ((nLists != null) && !nLists.isEmpty()) {
-                            for (final ListSchemaNode list : nLists) {
-
-                                notificationTypes.addAll(listToGenType(basePackageName, list));
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        return notificationTypes;
-    }
-
     private List<Type> augmentationToGenTypes(final String augmentPackageName,
                                               final AugmentationSchema augSchema) {
         if (augmentPackageName == null) {
@@ -404,8 +516,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
             }
             if ((augLists != null) && !augLists.isEmpty()) {
                 for (final ListSchemaNode list : augLists) {
-//                    final String listPackageName = packageNameForAugmentedType(
-//                            augBasePackageName, list.getPath());
                     genTypes.addAll(listToGenType(augBasePackageName, list));
                 }
             }
@@ -507,27 +617,22 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 final TypeDefinition<?> typeDef = leaf.getType();
 
                 Type returnType = null;
-                if (!(typeDef instanceof EnumTypeDefinition)
-                        && !isDerivedFromEnumerationType(typeDef)) {
+                if (!(typeDef instanceof EnumTypeDefinition)) {
                     returnType = typeProvider
                             .javaTypeForSchemaDefinitionType(typeDef);
                 } else {
-                    if (isImported(leaf.getPath(), typeDef.getPath())) {
-                        // TODO: resolving of imported enums as references to
-                        // GeneratedTypeData interface
-                    } else {
-                        final EnumTypeDefinition enumTypeDef = enumTypeDefFromExtendedType(typeDef);
-                        final EnumBuilder enumBuilder = resolveEnumFromTypeDefinition(
-                                enumTypeDef, leafName, typeBuilder);
-
-                        if (enumBuilder != null) {
-                            returnType = new ReferencedTypeImpl(
-                                    enumBuilder.getPackageName(),
-                                    enumBuilder.getName());
-                        }
+                    final EnumTypeDefinition enumTypeDef = enumTypeDefFromExtendedType(typeDef);
+                    final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
+                            enumTypeDef, leafName, typeBuilder);
+
+                    if (enumBuilder != null) {
+                        returnType = new ReferencedTypeImpl(
+                                enumBuilder.getPackageName(),
+                                enumBuilder.getName());
                     }
+                    ((TypeProviderImpl)typeProvider).putReferencedType(leaf
+                            .getPath(), returnType);
                 }
-
                 if (returnType != null) {
                     constructGetter(typeBuilder, leafName, leafDesc, returnType);
                     if (!leaf.isConfiguration()) {
@@ -540,26 +645,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return false;
     }
 
-    private boolean isImported(final SchemaPath leafPath,
-                               final SchemaPath typeDefPath) {
-        if ((leafPath != null) && (leafPath.getPath() != null)
-                && (typeDefPath != null) && (typeDefPath.getPath() != null)) {
-
-            final QName leafPathQName = leafPath.getPath().get(0);
-            final QName typePathQName = typeDefPath.getPath().get(0);
-
-            if ((leafPathQName != null)
-                    && (leafPathQName.getNamespace() != null)
-                    && (typePathQName != null)
-                    && (typePathQName.getNamespace() != null)) {
-
-                return !leafPathQName.getNamespace().equals(
-                        typePathQName.getNamespace());
-            }
-        }
-        return false;
-    }
-
     private boolean resolveLeafSchemaNodeAsProperty(
             final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
             boolean isReadOnly) {
@@ -767,23 +852,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
             addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
                     genTOBuilder, listKeys);
         }
-
-//        if (list.isAugmenting()) {
-//            for (final DataSchemaNode schemaNode : schemaNodes) {
-//                if (schemaNode.isAugmenting()) {
-//                    addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
-//                            genTOBuilder, listKeys);
-//                }
-//            }
-//        } else {
-//            for (final DataSchemaNode schemaNode : schemaNodes) {
-//                if (schemaNode.isAugmenting()) {
-//                    continue;
-//                }
-//                addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
-//                        genTOBuilder, listKeys);
-//            }
-//        }
         return typeBuildersToGenTypes(typeBuilder, genTOBuilder);
     }
 
@@ -818,7 +886,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
         } else if (schemaNode instanceof ListSchemaNode) {
             resolveListSchemaNode(basePackageName, typeBuilder, (ListSchemaNode) schemaNode);
         }
-
     }
 
     private List<Type> typeBuildersToGenTypes(
@@ -906,7 +973,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
         if (listKeys.size() > 0) {
             genTOBuilder = resolveListKey(packageName, list);
         }
-
         return genTOBuilder;
     }
 }
index 374ad8bf9251463b0dc9e86896a105b4f64f20e0..4a74ce6a9eca339893092f47776f40901f613bbe 100644 (file)
@@ -16,7 +16,7 @@ import org.opendaylight.controller.sal.binding.generator.spi.TypeProvider;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
 
-public class BaseYangTypes {
+public final class BaseYangTypes {
 
     private static Map<String, Type> typeMap = new HashMap<String, Type>();
 
@@ -32,6 +32,7 @@ public class BaseYangTypes {
     public static final Type UINT16_TYPE = Types.typeForClass(Integer.class);
     public static final Type UINT32_TYPE = Types.typeForClass(Long.class);
     public static final Type UINT64_TYPE = Types.typeForClass(BigInteger.class);
+    public static final Type BINARY_TYPE = Types.primitiveType("byte[]");
 
     static {
         typeMap.put("boolean", BOOLEAN_TYPE);
@@ -46,6 +47,7 @@ public class BaseYangTypes {
         typeMap.put("uint16", UINT16_TYPE);
         typeMap.put("uint32", UINT32_TYPE);
         typeMap.put("uint64", UINT64_TYPE);
+        typeMap.put("binary", BINARY_TYPE);
     }
 
     public static final TypeProvider BASE_YANG_TYPES_PROVIDER = new TypeProvider() {
index 0618efc8aec7f8a0732a8daafaf14e1c11203bbc..03824efed06ed868709cf696e96d231e74a57c12 100644 (file)
@@ -7,15 +7,7 @@
  */
 package org.opendaylight.controller.sal.binding.yang.types;
 
-import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.*;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil;
+import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
 import org.opendaylight.controller.binding.generator.util.Types;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
@@ -27,13 +19,7 @@ import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilde
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.controller.yang.model.api.DataSchemaNode;
-import org.opendaylight.controller.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.controller.yang.model.api.LeafSchemaNode;
-import org.opendaylight.controller.yang.model.api.Module;
-import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
-import org.opendaylight.controller.yang.model.api.SchemaContext;
-import org.opendaylight.controller.yang.model.api.TypeDefinition;
+import org.opendaylight.controller.yang.model.api.*;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
 import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition;
@@ -41,11 +27,19 @@ import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
 
-public class TypeProviderImpl implements TypeProvider {
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil.*;
+import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.*;
+
+public final class TypeProviderImpl implements TypeProvider {
 
     private final SchemaContext schemaContext;
-    private Map<String, Map<String, GeneratedTransferObject>> genTypeDefsContextMap;
-    private final List<GeneratedTransferObject> allTypeDefinitions;
+    private Map<String, Map<String, Type>> genTypeDefsContextMap;
+    private final Map<SchemaPath, Type> referencedTypes;
 
     public TypeProviderImpl(final SchemaContext schemaContext) {
         if (schemaContext == null) {
@@ -53,12 +47,23 @@ public class TypeProviderImpl implements TypeProvider {
         }
 
         this.schemaContext = schemaContext;
-        this.genTypeDefsContextMap = new HashMap<String, Map<String, GeneratedTransferObject>>();
-        allTypeDefinitions = resolveTypeDefsFromContext();
+        this.genTypeDefsContextMap = new HashMap<>();
+        this.referencedTypes = new HashMap<>();
+        resolveTypeDefsFromContext();
     }
 
-    public List<GeneratedTransferObject> getGeneratedTypeDefs() {
-        return allTypeDefinitions;
+    public void putReferencedType(final SchemaPath refTypePath,
+                                  final Type refType) {
+        if (refTypePath == null) {
+            throw new IllegalArgumentException("Path reference of " +
+                    "Enumeration Type Definition cannot be NULL!");
+        }
+
+        if (refType == null) {
+            throw new IllegalArgumentException("Reference to Enumeration " +
+                    "Type cannot be NULL!");
+        }
+        referencedTypes.put(refTypePath, refType);
     }
 
     /*
@@ -78,45 +83,97 @@ public class TypeProviderImpl implements TypeProvider {
     public Type javaTypeForSchemaDefinitionType(
             final TypeDefinition<?> typeDefinition) {
         Type returnType = null;
-        if (typeDefinition != null) {
-            final String typedefName = typeDefinition.getQName().getLocalName();
-            if (typeDefinition instanceof ExtendedType) {
-                final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
-
-                if (baseTypeDef instanceof LeafrefTypeDefinition) {
-                    final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
-                    returnType = provideTypeForLeafref(leafref);
-                } else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
-
-                } else if (baseTypeDef instanceof EnumTypeDefinition) {
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
-                    returnType = resolveEnumFromTypeDefinition(enumTypeDef,
-                            typedefName);
-                } else {
-
-                    final Module module = resolveModuleFromTypePath(schemaContext, typeDefinition);
-
-                    if (module != null) {
-                        final Map<String, GeneratedTransferObject> genTOs = genTypeDefsContextMap
-                                .get(module.getName());
-                        if (genTOs != null) {
-                            returnType = genTOs.get(typedefName);
-                        }
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
+        if (typeDefinition.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Type Definitions Local Name " +
+                    "cannot be NULL!");
+        }
+        final String typedefName = typeDefinition.getQName().getLocalName();
+        if (typeDefinition instanceof ExtendedType) {
+            final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
+
+            if (baseTypeDef instanceof LeafrefTypeDefinition) {
+                final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
+                returnType = provideTypeForLeafref(leafref);
+            } else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
+
+            } else if (baseTypeDef instanceof EnumTypeDefinition) {
+                final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
+                returnType = resolveEnumFromTypeDefinition(enumTypeDef,
+                        typedefName);
+            } else {
+                final Module module = findParentModuleForTypeDefinition(schemaContext,
+                        typeDefinition);
+                if (module != null) {
+                    final Map<String, Type> genTOs = genTypeDefsContextMap
+                            .get(module.getName());
+                    if (genTOs != null) {
+                        returnType = genTOs.get(typedefName);
+                    }
+                    if (returnType == null) {
+                        returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                                .javaTypeForSchemaDefinitionType(baseTypeDef);
                     }
                 }
+            }
+        } else {
+            if (typeDefinition instanceof LeafrefTypeDefinition) {
+                final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
+                returnType = provideTypeForLeafref(leafref);
+            } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
+
             } else {
-                if (typeDefinition instanceof LeafrefTypeDefinition) {
-                    final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
-                    returnType = provideTypeForLeafref(leafref);
-                } else if (typeDefinition instanceof EnumTypeDefinition) {
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDefinition;
-                    returnType = resolveEnumFromTypeDefinition(enumTypeDef,
-                            typedefName);
-                } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
+                returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                        .javaTypeForSchemaDefinitionType(typeDefinition);
+            }
+        }
+        //TODO: add throw exception when we will be able to resolve ALL yang
+        // types!
+//        if (returnType == null) {
+//            throw new IllegalArgumentException("Type Provider can't resolve " +
+//                    "type for specified Type Definition " + typedefName);
+//        }
+        return returnType;
+    }
 
-                } else {
-                    returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
-                            .javaTypeForSchemaDefinitionType(typeDefinition);
+    public Type generatedTypeForExtendedDefinitionType(
+            final TypeDefinition<?> typeDefinition) {
+        Type returnType = null;
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definitions Local Name " +
+                    "cannot be NULL!");
+        }
+
+        final String typedefName = typeDefinition.getQName().getLocalName();
+        if (typeDefinition instanceof ExtendedType) {
+            final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
+
+            if (!(baseTypeDef instanceof LeafrefTypeDefinition)
+                    && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
+                final Module module = findParentModuleForTypeDefinition(schemaContext,
+                        typeDefinition);
+
+                if (module != null) {
+                    final Map<String, Type> genTOs = genTypeDefsContextMap
+                            .get(module.getName());
+                    if (genTOs != null) {
+                        returnType = genTOs.get(typedefName);
+                    }
                 }
             }
         }
@@ -125,56 +182,55 @@ public class TypeProviderImpl implements TypeProvider {
 
     private TypeDefinition<?> baseTypeDefForExtendedType(
             final TypeDefinition<?> extendTypeDef) {
-        if (extendTypeDef != null) {
-            final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
-            if (baseTypeDef instanceof ExtendedType) {
-                return baseTypeDefForExtendedType(baseTypeDef);
-            } else {
-                return baseTypeDef;
-            }
+        if (extendTypeDef == null) {
+            throw new IllegalArgumentException("Type Definiition reference " +
+                    "cannot be NULL!");
         }
-        return null;
+        final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
+        if (baseTypeDef instanceof ExtendedType) {
+            return baseTypeDefForExtendedType(baseTypeDef);
+        } else {
+            return baseTypeDef;
+        }
+
     }
 
-    public Type baseTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
+    public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
         Type returnType = null;
-        if (typeDefinition != null) {
-            final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typeDefinition);
+        if (leafrefType == null) {
+            throw new IllegalArgumentException("Leafref Type Definition " +
+                    "reference cannot be NULL!");
+        }
 
-            if (baseTypeDefinition instanceof EnumTypeDefinition) {
-                final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDefinition;
-                final String enumName = enumTypeDef.getQName().getLocalName();
-                return resolveEnumFromTypeDefinition(enumTypeDef, enumName);
-            } else {
-                returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
-                        .javaTypeForSchemaDefinitionType(typeDefinition);
-            }
+        if (leafrefType.getPathStatement() == null) {
+            throw new IllegalArgumentException("The Path Statement for " +
+                    "Leafref Type Definition cannot be NULL!");
         }
-        return returnType;
-    }
 
-    public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
-        Type returnType = null;
-        if ((leafrefType != null) && (leafrefType.getPathStatement() != null)
-                && (leafrefType.getPath() != null)) {
+        final RevisionAwareXPath xpath = leafrefType.getPathStatement();
+        final String strXPath = xpath.toString();
 
-            final RevisionAwareXPath xpath = leafrefType.getPathStatement();
-            final String strXPath = xpath.toString();
+        if (strXPath != null) {
+            if (strXPath.matches(".*//[.* | .*//].*")) {
+                returnType = Types.typeForClass(Object.class);
+            } else {
+                final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
+                if (module != null) {
+                    final DataSchemaNode dataNode;
+                    if (xpath.isAbsolute()) {
+                        dataNode = findDataSchemaNode(schemaContext, module,
+                                xpath);
+                    } else {
+                        dataNode = findDataSchemaNodeForRelativeXPath(schemaContext,
+                                module, leafrefType, xpath);
+                    }
 
-            if (strXPath != null) {
-                if (strXPath.matches(".*//[.* | .*//].*")) {
-                    returnType = Types.typeForClass(Object.class);
-                } else {
-                    final Module module = resolveModuleFromTypePath(schemaContext, leafrefType);
-                    if (module != null) {
-                        final DataSchemaNode dataNode;
-                        if (xpath.isAbsolute()) {
-                            dataNode = findDataSchemaNode(schemaContext,
-                                    module, xpath);
-                        } else {
-                            dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module,
-                                            leafrefType, xpath);
-                        }
+                    if (leafContainsEnumDefinition(dataNode)) {
+                        returnType = referencedTypes.get(dataNode.getPath());
+                    } else if (leafListContainsEnumDefinition(dataNode)) {
+                        returnType = Types.listTypeFor(referencedTypes.get(
+                                dataNode.getPath()));
+                    } else {
                         returnType = resolveTypeFromDataSchemaNode(dataNode);
                     }
                 }
@@ -183,83 +239,112 @@ public class TypeProviderImpl implements TypeProvider {
         return returnType;
     }
 
-    private EnumBuilder resolveEnumFromTypeDefinition(
-            final EnumTypeDefinition enumTypeDef, final String enumName,
-            final GeneratedTypeBuilder typeBuilder) {
-        if ((enumTypeDef != null) && (typeBuilder != null)
-                && (enumTypeDef.getQName() != null)
-                && (enumTypeDef.getQName().getLocalName() != null)) {
-
-            final String enumerationName = BindingGeneratorUtil
-                    .parseToClassName(enumName);
-            final EnumBuilder enumBuilder = typeBuilder
-                    .addEnumeration(enumerationName);
-
-            if (enumBuilder != null) {
-                final List<EnumPair> enums = enumTypeDef.getValues();
-                if (enums != null) {
-                    int listIndex = 0;
-                    for (final EnumPair enumPair : enums) {
-                        if (enumPair != null) {
-                            final String enumPairName = BindingGeneratorUtil
-                                    .parseToClassName(enumPair.getName());
-                            Integer enumPairValue = enumPair.getValue();
-
-                            if (enumPairValue == null) {
-                                enumPairValue = listIndex;
-                            }
-                            enumBuilder.addValue(enumPairName, enumPairValue);
-                            listIndex++;
-                        }
-                    }
-                }
-                return enumBuilder;
+    private boolean leafContainsEnumDefinition(final DataSchemaNode dataNode) {
+        if (dataNode instanceof LeafSchemaNode) {
+            final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
+            if (leaf.getType() instanceof EnumTypeDefinition) {
+                return true;
             }
         }
-        return null;
+        return false;
+    }
+
+    private boolean leafListContainsEnumDefinition(
+            final DataSchemaNode dataNode) {
+        if (dataNode instanceof LeafListSchemaNode) {
+            final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
+            if (leafList.getType() instanceof EnumTypeDefinition) {
+                return true;
+            }
+        }
+        return false;
     }
 
     private Enumeration resolveEnumFromTypeDefinition(
             final EnumTypeDefinition enumTypeDef, final String enumName) {
-        if ((enumTypeDef != null) && (enumTypeDef.getQName() != null)
-                && (enumTypeDef.getQName().getLocalName() != null)) {
-
-            final String enumerationName = BindingGeneratorUtil
-                    .parseToClassName(enumName);
-
-            Module module = resolveModuleFromTypePath(schemaContext, enumTypeDef);
-
-            final String basePackageName = BindingGeneratorUtil
-                    .moduleNamespaceToPackageName(module);
-            final String packageName = BindingGeneratorUtil
-                    .packageNameForGeneratedType(basePackageName,
-                            enumTypeDef.getPath());
-
-            final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
-                    packageName, enumerationName);
-
-            if (enumBuilder != null) {
-                final List<EnumPair> enums = enumTypeDef.getValues();
-                if (enums != null) {
-                    int listIndex = 0;
-                    for (final EnumPair enumPair : enums) {
-                        if (enumPair != null) {
-                            final String enumPairName = BindingGeneratorUtil
-                                    .parseToClassName(enumPair.getName());
-                            Integer enumPairValue = enumPair.getValue();
-
-                            if (enumPairValue == null) {
-                                enumPairValue = listIndex;
-                            }
-                            enumBuilder.addValue(enumPairName, enumPairValue);
-                            listIndex++;
+        if (enumTypeDef == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition reference " +
+                    "cannot be NULL!");
+        }
+        if (enumTypeDef.getValues() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain at least ONE value definition!");
+        }
+        if (enumTypeDef.getQName() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain NON-NULL QName!");
+        }
+        if (enumTypeDef.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Local Name in " +
+                    "EnumTypeDefinition QName cannot be NULL!");
+        }
+
+        final String enumerationName = parseToClassName(enumName);
+
+        Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
+        final String basePackageName = moduleNamespaceToPackageName(module);
+
+        final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
+                basePackageName, enumerationName);
+        updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
+        return enumBuilder.toInstance(null);
+    }
+
+    private EnumBuilder resolveInnerEnumFromTypeDefinition(
+            final EnumTypeDefinition enumTypeDef, final String enumName,
+            final GeneratedTypeBuilder typeBuilder) {
+        if (enumTypeDef == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition reference " +
+                    "cannot be NULL!");
+        }
+        if (enumTypeDef.getValues() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain at least ONE value definition!");
+        }
+        if (enumTypeDef.getQName() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain NON-NULL QName!");
+        }
+        if (enumTypeDef.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Local Name in " +
+                    "EnumTypeDefinition QName cannot be NULL!");
+        }
+        if (typeBuilder == null) {
+            throw new IllegalArgumentException("Generated Type Builder " +
+                    "reference cannot be NULL!");
+        }
+
+        final String enumerationName = parseToClassName(enumName);
+        final EnumBuilder enumBuilder = typeBuilder
+                .addEnumeration(enumerationName);
+
+        updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
+
+        return enumBuilder;
+    }
+
+    private void updateEnumPairsFromEnumTypeDef(
+            final EnumTypeDefinition enumTypeDef,
+            final EnumBuilder enumBuilder) {
+        if (enumBuilder != null) {
+            final List<EnumPair> enums = enumTypeDef.getValues();
+            if (enums != null) {
+                int listIndex = 0;
+                for (final EnumPair enumPair : enums) {
+                    if (enumPair != null) {
+                        final String enumPairName = parseToClassName(enumPair
+                                .getName());
+                        Integer enumPairValue = enumPair.getValue();
+
+                        if (enumPairValue == null) {
+                            enumPairValue = listIndex;
                         }
+                        enumBuilder.addValue(enumPairName, enumPairValue);
+                        listIndex++;
                     }
                 }
-                return enumBuilder.toInstance(null);
             }
         }
-        return null;
     }
 
     private Type resolveTypeFromDataSchemaNode(final DataSchemaNode dataNode) {
@@ -276,129 +361,185 @@ public class TypeProviderImpl implements TypeProvider {
         return returnType;
     }
 
-    private List<GeneratedTransferObject> resolveTypeDefsFromContext() {
-        final List<GeneratedTransferObject> genTypeDefs = new ArrayList<GeneratedTransferObject>();
+    private void resolveTypeDefsFromContext() {
         final Set<Module> modules = schemaContext.getModules();
-        if (modules != null) {
-            for (final Module module : modules) {
-                if (module != null) {
-                    final String moduleName = module.getName();
-                    final String basePackageName = BindingGeneratorUtil
-                            .moduleNamespaceToPackageName(module);
-
-                    final Set<TypeDefinition<?>> typeDefinitions = module
-                            .getTypeDefinitions();
-
-                    if ((typeDefinitions != null) && (basePackageName != null)) {
-                        for (final TypeDefinition<?> typedef : typeDefinitions) {
-                            final GeneratedTransferObject genTransObj = toGeneratedTransferObject(
-                                    basePackageName, moduleName, typedef);
-                            if (genTransObj != null) {
-                                genTypeDefs.add(genTransObj);
-                            }
-                        }
-                        // for (final TypeDefinition<?> typedef :
-                        // typeDefinitions) {
-                        // addUnionGeneratedTypeDefinition(basePackageName,
-                        // module.getName(), typedef);
-                        // }
-                    }
+        if (modules == null) {
+            throw new IllegalArgumentException("Sef of Modules cannot be " +
+                    "NULL!");
+        }
+        for (final Module module : modules) {
+            if (module == null) {
+                continue;
+            }
+            final String moduleName = module.getName();
+            final String basePackageName = moduleNamespaceToPackageName(module);
+
+            final Set<TypeDefinition<?>> typeDefinitions = module
+                    .getTypeDefinitions();
+
+            final Map<String, Type> typeMap = new HashMap<>();
+            genTypeDefsContextMap.put(moduleName, typeMap);
+
+            if ((typeDefinitions != null) && (basePackageName != null)) {
+                for (final TypeDefinition<?> typedef : typeDefinitions) {
+                    typedefToGeneratedType(basePackageName, moduleName, typedef);
+                }
+                final List<ExtendedType> extUnions = UnionDependencySort
+                        .sort(typeDefinitions);
+                for (final ExtendedType extUnionType : extUnions) {
+                    addUnionGeneratedTypeDefinition(basePackageName, extUnionType);
                 }
             }
         }
-        return genTypeDefs;
     }
 
-    private GeneratedTransferObject toGeneratedTransferObject(
-            final String basePackageName, final String moduleName,
-            final TypeDefinition<?> typedef) {
+    private Type typedefToGeneratedType(final String basePackageName,
+                                        final String moduleName, final TypeDefinition<?> typedef) {
         if ((basePackageName != null) && (moduleName != null)
                 && (typedef != null) && (typedef.getQName() != null)) {
-            final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(
-                    basePackageName, typedef);
 
-            final String typedefName = typedef.getQName().getLocalName();
-            final String propertyName = BindingGeneratorUtil
-                    .parseToValidParamName(typedefName);
 
+            final String typedefName = typedef.getQName().getLocalName();
             final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
             if (!(baseTypeDefinition instanceof LeafrefTypeDefinition)
                     && !(baseTypeDefinition instanceof IdentityrefTypeDefinition)) {
-                Type returnType = null;
+                Type returnType;
                 if (baseTypeDefinition instanceof EnumTypeDefinition) {
                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDefinition;
                     returnType = resolveEnumFromTypeDefinition(enumTypeDef,
                             typedefName);
+
                 } else {
-                    returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                    final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
                             .javaTypeForSchemaDefinitionType(baseTypeDefinition);
-                }
 
+                    returnType = wrapJavaTypeIntoTO(basePackageName, typedef,
+                            javaType);
+                }
                 if (returnType != null) {
-                    final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
-                            .addProperty(propertyName);
-
-                    genPropBuilder.addReturnType(returnType);
-                    genTOBuilder.addEqualsIdentity(genPropBuilder);
-                    genTOBuilder.addHashIdentity(genPropBuilder);
-                    genTOBuilder.addToStringProperty(genPropBuilder);
-
-                    Map<String, GeneratedTransferObject> transferObjectsMap = genTypeDefsContextMap
-                            .get(moduleName);
-                    if (transferObjectsMap == null) {
-                        transferObjectsMap = new HashMap<String, GeneratedTransferObject>();
-                        genTypeDefsContextMap.put(moduleName,
-                                transferObjectsMap);
-                    }
-
-                    final GeneratedTransferObject transferObject = genTOBuilder
-                            .toInstance();
-                    if (transferObject != null) {
-                        transferObjectsMap.put(typedefName, transferObject);
-                        return transferObject;
+                    final Map<String, Type> typeMap = genTypeDefsContextMap.get
+                            (moduleName);
+                    if (typeMap != null) {
+                        typeMap.put(typedefName, returnType);
                     }
+                    return returnType;
                 }
             }
         }
         return null;
     }
 
+    private GeneratedTransferObject wrapJavaTypeIntoTO(
+            final String basePackageName, final TypeDefinition<?> typedef,
+            final Type javaType) {
+        if (javaType != null) {
+            final String typedefName = typedef.getQName().getLocalName();
+            final String propertyName = parseToValidParamName(typedefName);
+
+            final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(
+                    basePackageName, typedef);
+
+            final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
+                    .addProperty(propertyName);
+
+            genPropBuilder.addReturnType(javaType);
+            genTOBuilder.addEqualsIdentity(genPropBuilder);
+            genTOBuilder.addHashIdentity(genPropBuilder);
+            genTOBuilder.addToStringProperty(genPropBuilder);
+            return genTOBuilder.toInstance();
+        }
+        return null;
+    }
+
     private void addUnionGeneratedTypeDefinition(final String basePackageName,
-            final String moduleName, final TypeDefinition<?> typedef) {
-        if ((basePackageName != null) && (moduleName != null)
-                && (typedef != null) && (typedef.getQName() != null)) {
-            final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
+                                                 final TypeDefinition<?> typedef) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (typedef == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typedef.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
 
-            if ((baseTypeDefinition != null)
-                    && (baseTypeDefinition instanceof UnionTypeDefinition)) {
-                final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
-
-                final List<TypeDefinition<?>> unionTypes = unionTypeDef
-                        .getTypes();
-                final Map<String, GeneratedTransferObject> genTOsMap = genTypeDefsContextMap
-                        .get(moduleName);
-                final GeneratedTOBuilder unionGenTransObject = typedefToTransferObject(
-                        basePackageName, typedef);
-                if ((unionTypes != null) && (genTOsMap != null)
-                        && (unionGenTransObject != null)) {
-                    for (final TypeDefinition<?> unionType : unionTypes) {
-                        final String typeName = unionType.getQName()
-                                .getLocalName();
-                        final GeneratedTransferObject genTransferObject = genTOsMap
-                                .get(typeName);
-
-                        if (genTransferObject != null) {
-                            unionGenTransObject
-                                    .addProperty(
-                                            BindingGeneratorUtil
-                                                    .parseToValidParamName(genTransferObject
-                                                            .getName()))
-                                    .addReturnType(genTransferObject);
+        final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
+        if ((baseTypeDefinition != null)
+                && (baseTypeDefinition instanceof UnionTypeDefinition)) {
+            final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
+            final List<TypeDefinition<?>> unionTypes = unionTypeDef
+                    .getTypes();
+            final Module parentModule = findParentModuleForTypeDefinition(schemaContext,
+                    typedef);
+
+            Map<String, Type> genTOsMap = null;
+            if (parentModule != null && parentModule.getName() != null) {
+                genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
+            }
+
+            final GeneratedTOBuilder unionGenTransObject = typedefToTransferObject(
+                    basePackageName, typedef);
+            if ((unionTypes != null) && (unionGenTransObject != null)) {
+                for (final TypeDefinition<?> unionType : unionTypes) {
+                    final String typeName = unionType.getQName()
+                            .getLocalName();
+                    if (unionType instanceof ExtendedType) {
+                        final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext,
+                                unionType);
+                        if (unionTypeModule != null && unionTypeModule.getName() != null) {
+                            final Map<String, Type> innerGenTOs = genTypeDefsContextMap
+                                    .get(unionTypeModule.getName());
+
+                            final GeneratedTransferObject genTransferObject =
+                                    (GeneratedTransferObject) innerGenTOs.get(typeName);
+                            if (genTransferObject != null) {
+                                updateUnionTypeAsProperty(unionGenTransObject,
+                                        genTransferObject,
+                                        genTransferObject.getName());
+                            }
+                        }
+                    } else if (unionType instanceof EnumTypeDefinition) {
+                        final EnumBuilder
+                                enumBuilder = resolveInnerEnumFromTypeDefinition(
+                                (EnumTypeDefinition) unionType, typeName,
+                                unionGenTransObject);
+                        final Type enumRefType = new ReferencedTypeImpl(
+                                enumBuilder.getPackageName(),
+                                enumBuilder.getName());
+                        updateUnionTypeAsProperty(unionGenTransObject,
+                                enumRefType, typeName);
+                    } else {
+                        final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                                .javaTypeForSchemaDefinitionType(unionType);
+                        if (javaType != null) {
+                            updateUnionTypeAsProperty(unionGenTransObject,
+                                    javaType, typeName);
                         }
                     }
-                    genTOsMap.put(unionTypeDef.getQName().getLocalName(),
-                            unionGenTransObject.toInstance());
                 }
+                genTOsMap.put(typedef.getQName().getLocalName(),
+                        unionGenTransObject.toInstance());
+            }
+        }
+    }
+
+    private void updateUnionTypeAsProperty(
+            final GeneratedTOBuilder unionGenTransObject, final Type type,
+            final String propertyName) {
+        if (unionGenTransObject != null && type != null) {
+            final GeneratedPropertyBuilder propBuilder =
+                    unionGenTransObject.addProperty(parseToValidParamName(
+                            propertyName));
+            propBuilder.addReturnType(type);
+            propBuilder.setReadOnly(false);
+
+            if (!(type instanceof Enumeration)) {
+                unionGenTransObject.addEqualsIdentity(propBuilder);
+                unionGenTransObject.addHashIdentity(propBuilder);
+                unionGenTransObject.addToStringProperty(propBuilder);
             }
         }
     }
@@ -406,14 +547,13 @@ public class TypeProviderImpl implements TypeProvider {
     private GeneratedTOBuilder typedefToTransferObject(
             final String basePackageName, final TypeDefinition<?> typedef) {
 
-        final String packageName = BindingGeneratorUtil
-                .packageNameForGeneratedType(basePackageName, typedef.getPath());
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                typedef.getPath());
         final String typeDefTOName = typedef.getQName().getLocalName();
 
         if ((packageName != null) && (typedef != null)
                 && (typeDefTOName != null)) {
-            final String genTOName = BindingGeneratorUtil
-                    .parseToClassName(typeDefTOName);
+            final String genTOName = parseToClassName(typeDefTOName);
             final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(
                     packageName, genTOName);
 
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java
new file mode 100644 (file)
index 0000000..d19ac3f
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.yang.types;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.opendaylight.controller.yang.model.api.TypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.controller.yang.model.util.ExtendedType;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort.Node;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort.NodeImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class UnionDependencySort {
+    private static final Logger logger = LoggerFactory
+            .getLogger(UnionDependencySort.class);
+
+    public static List<ExtendedType> sort(
+            final Set<TypeDefinition<?>> typeDefinitions) {
+        if (typeDefinitions == null) {
+            logger.error("Set of Type Definitions cannot be NULL!");
+            throw new IllegalArgumentException("Set of Type Definitions " +
+                    "cannot be NULL!");
+        }
+
+        final Set<ExtendedType> extUnionTypes =
+                unionsFromTypeDefinitions(typeDefinitions);
+
+        final Set<Node> unsorted = unionTypesToUnionNodes(extUnionTypes);
+
+        final List<Node> sortedNodes = TopologicalSort.sort(unsorted);
+        return Lists.transform(sortedNodes, new Function<Node, ExtendedType>() {
+            @Override
+            public ExtendedType apply(Node input) {
+                return ((UnionNode) input).getUnionType();
+            }
+        });
+    }
+
+    private static Set<ExtendedType> unionsFromTypeDefinitions(
+            final Set<TypeDefinition<?>> typeDefinitions) {
+        final Set<ExtendedType> unions = Sets.newHashSet();
+
+        for (final TypeDefinition<?> typedef : typeDefinitions) {
+            if ((typedef != null) && (typedef.getBaseType() != null)) {
+                if (typedef instanceof ExtendedType
+                        && typedef.getBaseType() instanceof UnionTypeDefinition) {
+                    unions.add((ExtendedType) typedef);
+                }
+            }
+        }
+        return unions;
+    }
+
+    private static Set<Node> unionTypesToUnionNodes(
+            final Set<ExtendedType> extUnionTypes) {
+        final Map<ExtendedType, Node> nodeMap = Maps.newHashMap();
+        final Set<Node> resultNodes = Sets.newHashSet();
+
+        for (final ExtendedType unionType : extUnionTypes) {
+            final Node node = new UnionNode(unionType);
+            nodeMap.put(unionType, node);
+            resultNodes.add(node);
+        }
+
+        for (final Node node : resultNodes) {
+            final UnionNode unionNode = (UnionNode) node;
+            final ExtendedType extUnionType = unionNode.getUnionType();
+
+            final UnionTypeDefinition unionType = (UnionTypeDefinition)
+                    extUnionType.getBaseType();
+
+            final List<TypeDefinition<?>> innerTypes = unionType.getTypes();
+            for (final TypeDefinition<?> typedef : innerTypes) {
+                if (extUnionTypes.contains(typedef)) {
+                    final Node toNode = nodeMap.get(typedef);
+                    unionNode.addEdge(toNode);
+                }
+            }
+        }
+
+        return resultNodes;
+    }
+
+    private static UnionNode unionTypeToUnionNode(
+            final ExtendedType extUnionType,
+            final Set<ExtendedType> extUnionTypes) {
+        final UnionNode node = new UnionNode(extUnionType);
+
+        if (extUnionType.getBaseType() instanceof UnionTypeDefinition) {
+            final UnionTypeDefinition unionType = (UnionTypeDefinition)
+                    extUnionType.getBaseType();
+
+            final List<TypeDefinition<?>> innerTypes = unionType.getTypes();
+            for (final TypeDefinition<?> typedef : innerTypes) {
+                if ((typedef != null) && (typedef instanceof ExtendedType)
+                        && (typedef.getBaseType() instanceof UnionTypeDefinition)) {
+                    if (extUnionTypes.contains(typedef)) {
+                        node.addEdge(new UnionNode((ExtendedType) typedef));
+                    }
+                }
+            }
+        }
+
+        return node;
+    }
+
+    @VisibleForTesting
+    static final class UnionNode extends NodeImpl {
+        private final ExtendedType unionType;
+
+        UnionNode(ExtendedType unionType) {
+            this.unionType = unionType;
+        }
+
+        ExtendedType getUnionType() {
+            return unionType;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof UnionNode)) {
+                return false;
+            }
+            UnionNode unionNode = (UnionNode) o;
+            if (!unionType.equals(unionNode.unionType)) {
+                return false;
+            }
+            return true;
+        }
+
+        @Override
+        public int hashCode() {
+            return unionType.hashCode();
+        }
+
+        @Override
+        public String toString() {
+            return "UnionNode{" +
+                    "unionType=" + unionType +
+                    '}';
+        }
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java
new file mode 100644 (file)
index 0000000..aac64e8
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class AugmentRleativeXPathTest {
+
+    private final static List<File> augmentModels = new ArrayList<>();
+    private final static String augmentFolderPath = AugmentedTypeTest.class
+            .getResource("/augment-relative-xpath-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(augmentFolderPath);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                augmentModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void AugmentationWithRelativeXPathTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(augmentModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
index 448f610c49ba42265e080324c0ce0023c758b8f7..0fc4e43b0c4e299aef81c8d5d20990170f064bbc 100644 (file)
@@ -7,26 +7,22 @@
  */
 package org.opendaylight.controller.sal.binding.generator.impl;
 
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
-import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.*;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
 import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
 
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
 public class AugmentedTypeTest {
 
     private final static List<File> augmentModels = new ArrayList<>();
@@ -63,16 +59,16 @@ public class AugmentedTypeTest {
         GeneratedTransferObject gtTunnelKey = null;
         GeneratedType gtNetworkLink2 = null;
 
-        for(final Type type : genTypes) {
-            if(type.getName().equals("InterfaceKey") && type.getPackageName().contains("augment._abstract.topology")) {
+        for (final Type type : genTypes) {
+            if (type.getName().equals("InterfaceKey") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtInterfaceKey = (GeneratedTransferObject) type;
-            } else if(type.getName().equals("Interface") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("Interface") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtInterface = (GeneratedType) type;
-            } else if(type.getName().equals("Tunnel") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("Tunnel") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtTunnel = (GeneratedType) type;
-            } else if(type.getName().equals("TunnelKey") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("TunnelKey") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtTunnelKey = (GeneratedTransferObject) type;
-            } else if(type.getName().equals("NetworkLink2") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("NetworkLink2") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtNetworkLink2 = (GeneratedType) type;
             }
         }
@@ -90,8 +86,10 @@ public class AugmentedTypeTest {
         }
         assertNotNull("getIfcKeyMethod is null", getIfcKeyMethod);
         assertNotNull("getIfcKeyMethod.getReturnType() is null", getIfcKeyMethod.getReturnType());
-        assertFalse("getIfcKeyMethod.getReturnType() should not be Void", getIfcKeyMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getIfcKeyMethod.getReturnType().getName() must be InterfaceKey", getIfcKeyMethod.getReturnType().getName().equals("InterfaceKey"));
+        assertFalse("getIfcKeyMethod.getReturnType() should not be Void",
+                getIfcKeyMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getIfcKeyMethod.getReturnType().getName() must be InterfaceKey",
+                getIfcKeyMethod.getReturnType().getName().equals("InterfaceKey"));
 
         MethodSignature getHigherLayerIfMethod = null;
         for (final MethodSignature method : gtInterfaceMethods) {
@@ -101,9 +99,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("getHigherLayerIfMethod is null", getHigherLayerIfMethod);
-        assertNotNull("getHigherLayerIfMethod.getReturnType() is null", getHigherLayerIfMethod.getReturnType());
-        assertFalse("getHigherLayerIfMethod.getReturnType() should not be Void", getHigherLayerIfMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getHigherLayerIfMethod.getReturnType().getName() must be List", getHigherLayerIfMethod.getReturnType().getName().equals("List"));
+        assertNotNull("getHigherLayerIfMethod.getReturnType() is null",
+                getHigherLayerIfMethod.getReturnType());
+        assertFalse("getHigherLayerIfMethod.getReturnType() should not be Void",
+                getHigherLayerIfMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getHigherLayerIfMethod.getReturnType().getName() must be List",
+                getHigherLayerIfMethod.getReturnType().getName().equals("List"));
 
         // 'InterfaceKey'
         assertNotNull("gtInterfaceKey is null", gtInterfaceKey);
@@ -118,8 +119,10 @@ public class AugmentedTypeTest {
         }
         assertNotNull("gtInterfaceId is null", gtInterfaceId);
         assertNotNull("gtInterfaceId.getReturnType() is null", gtInterfaceId.getReturnType());
-        assertFalse("gtInterfaceId.getReturnType() should not be Void", gtInterfaceId.getReturnType().equals("java.lang.Void"));
-        assertTrue("gtInterfaceId.getReturnType().getName() must be String", gtInterfaceId.getReturnType().getName().equals("String"));
+        assertFalse("gtInterfaceId.getReturnType() should not be Void",
+                gtInterfaceId.getReturnType().equals("java.lang.Void"));
+        assertTrue("gtInterfaceId.getReturnType().getName() must be String",
+                gtInterfaceId.getReturnType().getName().equals("String"));
 
         // 'Tunnel'
         assertNotNull("gtTunnel is null", gtTunnel);
@@ -133,9 +136,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("getTunnelKeyMethod is null", getTunnelKeyMethod);
-        assertNotNull("getTunnelKeyMethod.getReturnType()", getTunnelKeyMethod.getReturnType());
-        assertFalse("getTunnelKeyMethod.getReturnType() should not be Void", getTunnelKeyMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getTunnelKeyMethod.getReturnType().getName() must be TunnelKey", getTunnelKeyMethod.getReturnType().getName().equals("TunnelKey"));
+        assertNotNull("getTunnelKeyMethod.getReturnType()",
+                getTunnelKeyMethod.getReturnType());
+        assertFalse("getTunnelKeyMethod.getReturnType() should not be Void",
+                getTunnelKeyMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getTunnelKeyMethod.getReturnType().getName() must be TunnelKey",
+                getTunnelKeyMethod.getReturnType().getName().equals("TunnelKey"));
 
         // 'TunnelKey'
         assertNotNull("gtTunnelKey is null", gtTunnelKey);
@@ -149,9 +155,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("gtTunnelId is null", gtTunnelId);
-        assertNotNull("gtTunnelId.getReturnType() is null", gtTunnelId.getReturnType());
-        assertFalse("gtTunnelId.getReturnType() should not be Void", gtTunnelId.getReturnType().equals("java.lang.Void"));
-        assertTrue("gtTunnelId.getReturnType().getName() must be Integer", gtTunnelId.getReturnType().getName().equals("Integer"));
+        assertNotNull("gtTunnelId.getReturnType() is null",
+                gtTunnelId.getReturnType());
+        assertFalse("gtTunnelId.getReturnType() should not be Void",
+                gtTunnelId.getReturnType().equals("java.lang.Void"));
+        assertTrue("gtTunnelId.getReturnType().getName() must be Integer",
+                gtTunnelId.getReturnType().getName().equals("Integer"));
 
         // 'NetworkLink2'
         assertNotNull("gtNetworkLink2 is null", gtNetworkLink2);
@@ -160,21 +169,18 @@ public class AugmentedTypeTest {
         assertNotNull("networkLink2Methods is null", networkLink2Methods);
 
 //        FIXME: in some cases getIfcMethod is null which causes test fail. fix ASAP
-//        MethodSignature getIfcMethod = null;
-//        for (MethodSignature method : networkLink2Methods) {
-//            if (method.getName().equals("getInterface")) {
-//                getIfcMethod = method;
-//                break;
-//            }
-//        }
+//      MethodSignature getIfcMethod = null;
+//      for (MethodSignature method : networkLink2Methods) {
+//          if (method.getName().equals("getInterface")) {
+//              getIfcMethod = method;
+//              break;
+//          }
+//      }
 //
-//        assertNotNull("getIfcMethod is null", getIfcMethod);
-//        assertNotNull("getIfcMethod.getReturnType() is null",
-//                getIfcMethod.getReturnType());
-//        assertFalse("getIfcMethod.getReturnType() should not be Void",
-//                getIfcMethod.getReturnType().equals("java.lang.Void"));
-//        assertTrue("getIfcMethod.getReturnType().getName() must be String",
-//                getIfcMethod.getReturnType().getName().equals("String"));
+//      assertNotNull("getIfcMethod is null", getIfcMethod);
+//      assertNotNull("getIfcMethod.getReturnType() is null", getIfcMethod.getReturnType());
+//      assertFalse("getIfcMethod.getReturnType() should not be Void", getIfcMethod.getReturnType().equals("java.lang.Void"));
+//      assertTrue("getIfcMethod.getReturnType().getName() must be String", getIfcMethod.getReturnType().getName().equals("String"));
     }
 
     @Test
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java
new file mode 100644 (file)
index 0000000..a3d2d27
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+*
+* This program and the accompanying materials are made available under the
+* terms of the Eclipse Public License v1.0 which accompanies this distribution,
+* and is available at http://www.eclipse.org/legal/epl-v10.html
+*/
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class BinaryTypeTest {
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/binary-type-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void binaryTypeTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java
new file mode 100644 (file)
index 0000000..6a0e114
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import org.junit.Test;
+import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class GenEnumResolvingTest {
+
+    private SchemaContext resolveSchemaContextFromFiles(
+            final String... yangFiles) {
+        final YangModelParser parser = new YangParserImpl();
+
+        final List<File> inputFiles = new ArrayList<File>();
+        for (int i = 0; i < yangFiles.length; ++i) {
+            inputFiles.add(new File(yangFiles[i]));
+        }
+
+        final Set<Module> modules = parser.parseYangModels(inputFiles);
+        return parser.resolveSchemaContext(modules);
+    }
+
+    @Test
+    public void testLeafEnumResolving() {
+        final String ietfInterfacesPath = getClass().getResource(
+                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
+        final String ifTypePath = getClass().getResource(
+                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
+        final String yangTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
+
+        final SchemaContext context = resolveSchemaContextFromFiles(
+                ietfInterfacesPath, ifTypePath, yangTypesPath);
+        assertTrue(context != null);
+
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertTrue(genTypes != null);
+
+        assertEquals("Expected count of all Generated Types from yang models " +
+                "is 22", 22, genTypes.size());
+
+        GeneratedType genInterface = null;
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedType) {
+                if (type.getName().equals("Interface")) {
+                    genInterface = (GeneratedType) type;
+                }
+            }
+        }
+        assertNotNull("Generated Type Interface is not present in list of " +
+                "Generated Types", genInterface);
+
+        Enumeration linkUpDownTrapEnable = null;
+        Enumeration operStatus = null;
+        final List<Enumeration> enums = genInterface.getEnumDefintions();
+        assertNotNull("Generated Type Interface cannot contain NULL reference" +
+                " to Enumeration types!", enums);
+        assertEquals("Generated Type Interface MUST contain 2 Enumeration " +
+                "Types", 2, enums.size());
+        for (final Enumeration e : enums) {
+            if (e.getName().equals("LinkUpDownTrapEnable")) {
+                linkUpDownTrapEnable = e;
+            } else if (e.getName().equals("OperStatus")) {
+                operStatus = e;
+            }
+        }
+
+        assertNotNull("Expected Enum LinkUpDownTrapEnable, but was NULL!",
+                linkUpDownTrapEnable);
+        assertNotNull("Expected Enum OperStatus, but was NULL!", operStatus);
+
+        assertNotNull("Enum LinkUpDownTrapEnable MUST contain Values definition " +
+                "not NULL reference!", linkUpDownTrapEnable.getValues());
+        assertNotNull("Enum OperStatus MUST contain Values definition not " +
+                "NULL reference!", operStatus.getValues());
+        assertEquals("Enum LinkUpDownTrapEnable MUST contain 2 values!", 2,
+                linkUpDownTrapEnable.getValues().size());
+        assertEquals("Enum OperStatus MUST contain 7 values!", 7,
+                operStatus.getValues().size());
+
+        final List<MethodSignature> methods = genInterface
+                .getMethodDefinitions();
+
+        assertNotNull("Generated Interface cannot contain NULL reference for " +
+                "Method Signature Definitions!", methods);
+
+        assertEquals("Expected count of method signature definitions is 26",
+                26, methods.size());
+        Enumeration ianaIfType = null;
+        for (final MethodSignature method : methods) {
+            if (method.getName().equals("getType")) {
+                if (method.getReturnType() instanceof Enumeration) {
+                    ianaIfType = (Enumeration)method.getReturnType();
+                }
+            }
+        }
+
+        assertNotNull("Method getType MUST return Enumeration Type, " +
+                "not NULL reference!", ianaIfType);
+        assertEquals("Enumeration getType MUST contain 272 values!", 272,
+                ianaIfType.getValues().size());
+    }
+
+    @Test
+    public void testTypedefEnumResolving() {
+        final String ianaIfTypePath = getClass().getResource(
+                "/leafref-test-models/iana-if-type@2012-06-05.yang").getPath();
+
+        final SchemaContext context = resolveSchemaContextFromFiles(ianaIfTypePath);
+        assertTrue(context != null);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertTrue(genTypes != null);
+        assertEquals(2, genTypes.size());
+
+        final Type type = genTypes.get(1);
+        assertTrue(type instanceof Enumeration);
+
+        final Enumeration enumer = (Enumeration) type;
+        assertEquals("Enumeration type MUST contain 272 values!", 272,
+                enumer.getValues().size());
+    }
+
+    @Test
+    public void testLeafrefEnumResolving() {
+        final String ietfInterfacesPath = getClass().getResource(
+                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
+        final String ifTypePath = getClass().getResource(
+                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
+        final String yangTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
+        final String topologyPath = getClass().getResource(
+                "/enum-test-models/abstract-topology@2013-02-08.yang")
+                .getPath();
+        final String inetTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-inet-types@2010-09-24.yang")
+                .getPath();
+        final SchemaContext context = resolveSchemaContextFromFiles(
+                ietfInterfacesPath, ifTypePath, yangTypesPath, topologyPath,
+                inetTypesPath);
+
+        assertNotNull(context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertNotNull(genTypes);
+        assertTrue(!genTypes.isEmpty());
+
+        GeneratedType genInterface = null;
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedType) {
+                if (type.getPackageName().equals("org.opendaylight.yang.gen.v1.urn.model._abstract.topology.rev201328.topology.interfaces")
+                        && type.getName().equals("Interface")) {
+                    genInterface = (GeneratedType) type;
+                }
+            }
+        }
+        assertNotNull("Generated Type Interface is not present in list of " +
+                "Generated Types", genInterface);
+
+        Type linkUpDownTrapEnable = null;
+        Type operStatus = null;
+        final List<MethodSignature> methods = genInterface.getMethodDefinitions();
+        assertNotNull("Generated Type Interface cannot contain NULL reference" +
+                " to Enumeration types!", methods);
+        assertEquals("Generated Type Interface MUST contain 7 Methods ",
+                7, methods.size());
+        for (final MethodSignature method : methods) {
+            if (method.getName().equals("getLinkUpDownTrapEnable")) {
+                linkUpDownTrapEnable = method.getReturnType();
+            } else if (method.getName().equals("getOperStatus")) {
+                operStatus = method.getReturnType();
+            }
+        }
+
+        assertNotNull("Expected Referenced Enum LinkUpDownTrapEnable, but was NULL!",
+                linkUpDownTrapEnable);
+        assertTrue("Expected LinkUpDownTrapEnable of type ReferencedTypeImpl",
+                linkUpDownTrapEnable instanceof ReferencedTypeImpl);
+        assertEquals(linkUpDownTrapEnable.getPackageName(),
+                "org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev20121115.interfaces.Interface");
+
+        assertNotNull("Expected Referenced Enum OperStatus, but was NULL!",
+                operStatus);
+        assertTrue("Expected OperStatus of type ReferencedTypeImpl",
+                operStatus instanceof  ReferencedTypeImpl);
+        assertEquals(operStatus.getPackageName(),
+                "org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev20121115.interfaces.Interface");
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java
new file mode 100644 (file)
index 0000000..c6d9a28
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.*;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class GenTypesSubSetTest {
+
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/leafref-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void genTypesFromSubsetOfTwoModulesTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        final Set<Module> toGenModules = new HashSet<>();
+        for (final Module module : modules) {
+            if (module.getName().equals("abstract-topology")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("ietf-interfaces")) {
+                toGenModules.add(module);
+            }
+        }
+
+        assertEquals("Set of to Generate Modules must contain 2 modules", 2,
+                toGenModules.size());
+        assertNotNull("Schema Context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+        assertEquals("Expected Generated Types from provided sub set of " +
+                "modules should be 23!", 23,
+                genTypes.size());
+    }
+
+    @Test
+    public void genTypesFromSubsetOfThreeModulesTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        final Set<Module> toGenModules = new HashSet<>();
+        for (final Module module : modules) {
+            if (module.getName().equals("abstract-topology")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("ietf-interfaces")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("iana-if-type")) {
+                toGenModules.add(module);
+            }
+        }
+
+        assertEquals("Set of to Generate Modules must contain 3 modules", 3,
+                toGenModules.size());
+
+        assertNotNull("Schema Context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+        assertEquals("Expected Generated Types from provided sub set of "  +
+                "modules should be 25!", 25, genTypes.size());
+    }
+}
index 66c293eebc5beadf52cb7614dacf5f5bad2a5c4e..0010733c43939b497dc93fe1ccc91f9e314ebd56 100644 (file)
@@ -42,53 +42,6 @@ public class GeneratedTypesTest {
         return parser.resolveSchemaContext(modules);
     }
 
-    @Test
-    public void testLeafEnumResolving() {
-        final String ietfInterfacesPath = getClass().getResource(
-                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
-        final String ifTypePath = getClass().getResource(
-                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
-        final String yangTypesPath = getClass().getResource(
-                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
-
-        final SchemaContext context = resolveSchemaContextFromFiles(
-                ietfInterfacesPath, ifTypePath, yangTypesPath);
-        assertTrue(context != null);
-
-        final BindingGenerator bindingGen = new BindingGeneratorImpl();
-        final List<Type> genTypes = bindingGen.generateTypes(context);
-        assertTrue(genTypes != null);
-    }
-
-    @Test
-    public void testTypedefEnumResolving() {
-        final String ianaIfTypePath = getClass().getResource(
-                "/leafref-test-models/iana-if-type@2012-06-05.yang").getPath();
-
-        final SchemaContext context = resolveSchemaContextFromFiles(ianaIfTypePath);
-        assertTrue(context != null);
-        final BindingGenerator bindingGen = new BindingGeneratorImpl();
-        final List<Type> genTypes = bindingGen.generateTypes(context);
-        assertTrue(genTypes != null);
-        assertEquals(2, genTypes.size());
-
-        final Type type = genTypes.get(1);
-        assertTrue(type instanceof GeneratedTransferObject);
-
-        final GeneratedTransferObject genTransObj = (GeneratedTransferObject) type;
-        final List<GeneratedProperty> properties = genTransObj.getProperties();
-        assertNotNull(properties);
-        assertEquals(1, properties.size());
-
-        GeneratedProperty property = properties.get(0);
-        assertNotNull(property);
-        assertNotNull(property.getReturnType());
-
-        assertTrue(property.getReturnType() instanceof Enumeration);
-        final Enumeration enumer = (Enumeration) property.getReturnType();
-        assertEquals(272, enumer.getValues().size());
-    }
-
     @Test
     public void testMultipleModulesResolving() {
         final String topologyPath = getClass().getResource(
@@ -103,7 +56,7 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(24, genTypes.size());
+        assertEquals(27, genTypes.size());
     }
 
     @Test
@@ -140,7 +93,7 @@ public class GeneratedTypesTest {
         final BindingGenerator bindingGen = new BindingGeneratorImpl();
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
-        assertEquals(50, genTypes.size());
+        assertEquals(53, genTypes.size());
         assertTrue(genTypes != null);
 
         GeneratedTransferObject gtIfcKey = null;
@@ -310,8 +263,8 @@ public class GeneratedTypesTest {
         assertTrue(genTypes != null);
         assertEquals(3, genTypes.size());
 
-        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(0);
-        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(2);
 
         assertEquals("SimpleContainer", simpleContainer.getName());
         assertEquals("NestedContainer", nestedContainer.getName());
@@ -388,8 +341,8 @@ public class GeneratedTypesTest {
         assertTrue(genTypes != null);
         assertEquals(3, genTypes.size());
 
-        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(0);
-        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(2);
 
         assertEquals("SimpleContainer", simpleContainer.getName());
         assertEquals("NestedContainer", nestedContainer.getName());
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java
new file mode 100644 (file)
index 0000000..7ff6283
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class UnionTypeDefTest {
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/union-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void unionTypeResolvingTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang
new file mode 100644 (file)
index 0000000..d80a3e9
--- /dev/null
@@ -0,0 +1,101 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types { 
+        prefix "inet"; 
+        revision-date 2010-09-24;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed 
+    to be used solely for network representation. This module SHOULD be used as base 
+    module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "http://www.opendaylight.org/";
+    }
+    
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains 
+        only Network Nodes and Network Links. Each topology MUST be identified by unique 
+        topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. 
+            To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) 
+                Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that 
+                many links are originated from one node and end up in same remote node). 
+                To ensure that we would always know to distinguish between links, every link 
+                SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang
new file mode 100644 (file)
index 0000000..051b2d9
--- /dev/null
@@ -0,0 +1,69 @@
+module augment-abstract-topology {
+    yang-version 1;
+    namespace "urn:model:augment:abstract:topology";
+    prefix "atp";
+
+    import ietf-inet-types { 
+        prefix "inet";
+        revision-date 2010-09-24;
+    }
+
+    import ietf-interfaces {
+        prefix "if";
+        revision-date 2012-11-15;
+    }
+
+    import abstract-topology {
+        prefix "at";
+        revision-date 2013-02-08;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    revision "2013-05-03" {
+        reference "http://www.opendaylight.org/";
+    }
+
+    augment "at:topology" {
+        container interfaces {
+            list interface {
+                key "interface-id";
+
+                leaf interface-id {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:name";
+                    }
+                }
+
+                leaf-list higher-layer-if {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:higher-layer-if";
+                    }
+                }
+            }
+        }
+    }
+
+    augment "at:topology/at:network-links/at:network-link" {
+        container tunnels {
+            list tunnel {
+                key "tunnel-id";
+
+                leaf tunnel-id {
+                    type leafref {
+                        path "../../../link-id";
+                    }
+                }
+            }
+        }
+    }
+
+    augment "at:topology/at:network-links/at:network-link" {
+        leaf interface {
+            type leafref {
+                path "../../../atp:interfaces/atp:interface/atp:interface-id";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang
new file mode 100644 (file)
index 0000000..a7fa137
--- /dev/null
@@ -0,0 +1,1516 @@
+module iana-if-type {
+  namespace "urn:ietf:params:xml:ns:yang:iana-if-type";
+  prefix ianaift;
+
+  organization "IANA";
+  contact
+    "        Internet Assigned Numbers Authority
+
+     Postal: ICANN
+             4676 Admiralty Way, Suite 330
+             Marina del Rey, CA 90292
+
+     Tel:    +1 310 823 9358
+     E-Mail: iana&iana.org";
+  description
+    "This YANG module defines the iana-if-type typedef, which
+     contains YANG definitions for IANA-registered interface types.
+
+     This YANG module is maintained by IANA, and reflects the
+     'ifType definitions' registry.
+
+     The latest revision of this YANG module can be obtained from
+     the IANA web site.
+
+     Copyright (c) 2011 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC XXXX; see
+     the RFC itself for full legal notices.";
+  // RFC Ed.: replace XXXX with actual RFC number and remove this
+  // note.
+
+  // RFC Ed.: update the date below with the date of RFC publication
+  // and remove this note.
+  revision 2012-06-05 {
+    description
+      "Initial revision.";
+    reference
+      "RFC XXXX: TITLE";
+  }
+
+  typedef iana-if-type {
+    type enumeration {
+      enum "other" {
+        value 1;
+        description
+          "None of the following";
+      }
+      enum "regular1822" {
+        value 2;
+      }
+      enum "hdh1822" {
+        value 3;
+      }
+      enum "ddnX25" {
+        value 4;
+      }
+      enum "rfc877x25" {
+        value 5;
+        reference
+          "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer";
+      }
+      enum "ethernetCsmacd" {
+        value 6;
+        description
+          "For all ethernet-like interfaces, regardless of speed,
+           as per RFC3635.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "iso88023Csmacd" {
+        value 7;
+        status deprecated;
+        description
+          "Deprecated via RFC3635.
+           Use ethernetCsmacd(6) instead.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "iso88024TokenBus" {
+        value 8;
+      }
+      enum "iso88025TokenRing" {
+        value 9;
+      }
+      enum "iso88026Man" {
+        value 10;
+      }
+      enum "starLan" {
+        value 11;
+        status deprecated;
+        description
+          "Deprecated via RFC3635.
+           Use ethernetCsmacd(6) instead.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "proteon10Mbit" {
+        value 12;
+      }
+      enum "proteon80Mbit" {
+        value 13;
+      }
+      enum "hyperchannel" {
+        value 14;
+      }
+      enum "fddi" {
+        value 15;
+        reference
+          "RFC 1512 - FDDI Management Information Base";
+      }
+      enum "lapb" {
+        value 16;
+        reference
+          "RFC 1381 - SNMP MIB Extension for X.25 LAPB";
+      }
+      enum "sdlc" {
+        value 17;
+      }
+      enum "ds1" {
+        value 18;
+        description
+          "DS1-MIB";
+        reference
+          "RFC 4805 - Definitions of Managed Objects for the
+                      DS1, J1, E1, DS2, and E2 Interface Types";
+      }
+      enum "e1" {
+        value 19;
+        status obsolete;
+        description
+          "Obsolete see DS1-MIB";
+        reference
+          "RFC 4805 - Definitions of Managed Objects for the
+                      DS1, J1, E1, DS2, and E2 Interface Types";
+      }
+      enum "basicISDN" {
+        value 20;
+        description
+          "see also RFC2127";
+      }
+      enum "primaryISDN" {
+        value 21;
+      }
+      enum "propPointToPointSerial" {
+        value 22;
+        description
+          "proprietary serial";
+      }
+      enum "ppp" {
+        value 23;
+      }
+      enum "softwareLoopback" {
+        value 24;
+      }
+      enum "eon" {
+        value 25;
+        description
+          "CLNP over IP";
+      }
+      enum "ethernet3Mbit" {
+        value 26;
+      }
+      enum "nsip" {
+        value 27;
+        description
+          "XNS over IP";
+      }
+      enum "slip" {
+        value 28;
+        description
+          "generic SLIP";
+      }
+      enum "ultra" {
+        value 29;
+        description
+          "ULTRA technologies";
+      }
+      enum "ds3" {
+        value 30;
+        description
+          "DS3-MIB";
+        reference
+          "RFC 3896 - Definitions of Managed Objects for the
+                      DS3/E3 Interface Type";
+      }
+      enum "sip" {
+        value 31;
+        description
+          "SMDS, coffee";
+        reference
+          "RFC 1694 - Definitions of Managed Objects for SMDS
+                      Interfaces using SMIv2";
+      }
+      enum "frameRelay" {
+        value 32;
+        description
+          "DTE only.";
+        reference
+          "RFC 2115 - Management Information Base for Frame Relay
+                      DTEs Using SMIv2";
+      }
+      enum "rs232" {
+        value 33;
+        reference
+          "RFC 1659 - Definitions of Managed Objects for RS-232-like
+                      Hardware Devices using SMIv2";
+      }
+      enum "para" {
+        value 34;
+        description
+          "parallel-port";
+        reference
+          "RFC 1660 - Definitions of Managed Objects for
+                      Parallel-printer-like Hardware Devices using
+                      SMIv2";
+      }
+      enum "arcnet" {
+        value 35;
+        description
+          "arcnet";
+      }
+      enum "arcnetPlus" {
+        value 36;
+        description
+          "arcnet plus";
+      }
+      enum "atm" {
+        value 37;
+        description
+          "ATM cells";
+      }
+      enum "miox25" {
+        value 38;
+        reference
+          "RFC 1461 - SNMP MIB extension for Multiprotocol
+                      Interconnect over X.25";
+      }
+      enum "sonet" {
+        value 39;
+        description
+          "SONET or SDH";
+      }
+      enum "x25ple" {
+        value 40;
+        reference
+          "RFC 2127 - ISDN Management Information Base using SMIv2";
+      }
+      enum "iso88022llc" {
+        value 41;
+      }
+      enum "localTalk" {
+        value 42;
+      }
+      enum "smdsDxi" {
+        value 43;
+      }
+      enum "frameRelayService" {
+        value 44;
+        description
+          "FRNETSERV-MIB";
+        reference
+          "RFC 2954 - Definitions of Managed Objects for Frame
+                      Relay Service";
+      }
+      enum "v35" {
+        value 45;
+      }
+      enum "hssi" {
+        value 46;
+      }
+      enum "hippi" {
+        value 47;
+      }
+      enum "modem" {
+        value 48;
+        description
+          "Generic modem";
+      }
+      enum "aal5" {
+        value 49;
+        description
+          "AAL5 over ATM";
+      }
+      enum "sonetPath" {
+        value 50;
+      }
+      enum "sonetVT" {
+        value 51;
+      }
+      enum "smdsIcip" {
+        value 52;
+        description
+          "SMDS InterCarrier Interface";
+      }
+      enum "propVirtual" {
+        value 53;
+        description
+          "proprietary virtual/internal";
+        reference
+          "RFC 2863 - The Interfaces Group MIB";
+      }
+      enum "propMultiplexor" {
+        value 54;
+        description
+          "proprietary multiplexing";
+        reference
+          "RFC 2863 - The Interfaces Group MIB";
+      }
+      enum "ieee80212" {
+        value 55;
+        description
+          "100BaseVG";
+      }
+      enum "fibreChannel" {
+        value 56;
+        description
+          "Fibre Channel";
+      }
+      enum "hippiInterface" {
+        value 57;
+        description
+          "HIPPI interfaces";
+      }
+      enum "frameRelayInterconnect" {
+        value 58;
+        status obsolete;
+        description
+          "Obsolete use either
+           frameRelay(32) or frameRelayService(44).";
+      }
+      enum "aflane8023" {
+        value 59;
+        description
+          "ATM Emulated LAN for 802.3";
+      }
+      enum "aflane8025" {
+        value 60;
+        description
+          "ATM Emulated LAN for 802.5";
+      }
+      enum "cctEmul" {
+        value 61;
+        description
+         "ATM Emulated circuit";
+      }
+      enum "fastEther" {
+        value 62;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635.
+          ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "isdn" {
+        value 63;
+        description
+          "ISDN and X.25";
+        reference
+          "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN
+                      in the Packet Mode";
+      }
+      enum "v11" {
+        value 64;
+        description
+         "CCITT V.11/X.21";
+      }
+      enum "v36" {
+        value 65;
+        description
+          "CCITT V.36";
+      }
+      enum "g703at64k" {
+        value 66;
+        description
+          "CCITT G703 at 64Kbps";
+      }
+      enum "g703at2mb" {
+        value 67;
+        status obsolete;
+        description
+          "Obsolete see DS1-MIB";
+      }
+      enum "qllc" {
+        value 68;
+        description
+          "SNA QLLC";
+      }
+      enum "fastEtherFX" {
+        value 69;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635
+          ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "channel" {
+        value 70;
+        description
+          "channel";
+      }
+      enum "ieee80211" {
+        value 71;
+        description
+          "radio spread spectrum";
+      }
+      enum "ibm370parChan" {
+        value 72;
+        description
+          "IBM System 360/370 OEMI Channel";
+      }
+      enum "escon" {
+        value 73;
+        description
+          "IBM Enterprise Systems Connection";
+      }
+      enum "dlsw" {
+        value 74;
+        description
+          "Data Link Switching";
+      }
+      enum "isdns" {
+        value 75;
+        description
+          "ISDN S/T interface";
+      }
+      enum "isdnu" {
+        value 76;
+        description
+          "ISDN U interface";
+      }
+      enum "lapd" {
+        value 77;
+        description
+          "Link Access Protocol D";
+      }
+      enum "ipSwitch" {
+        value 78;
+        description
+          "IP Switching Objects";
+      }
+      enum "rsrb" {
+        value 79;
+        description
+          "Remote Source Route Bridging";
+      }
+      enum "atmLogical" {
+        value 80;
+        description
+          "ATM Logical Port";
+        reference
+          "RFC 3606 - Definitions of Supplemental Managed Objects
+                      for ATM Interface";
+      }
+      enum "ds0" {
+        value 81;
+        description
+          "Digital Signal Level 0";
+        reference
+          "RFC 2494 - Definitions of Managed Objects for the DS0
+                      and DS0 Bundle Interface Type";
+      }
+      enum "ds0Bundle" {
+        value 82;
+        description
+          "group of ds0s on the same ds1";
+        reference
+          "RFC 2494 - Definitions of Managed Objects for the DS0
+                      and DS0 Bundle Interface Type";
+      }
+      enum "bsc" {
+        value 83;
+        description
+          "Bisynchronous Protocol";
+      }
+      enum "async" {
+        value 84;
+        description
+          "Asynchronous Protocol";
+      }
+      enum "cnr" {
+        value 85;
+        description
+          "Combat Net Radio";
+      }
+      enum "iso88025Dtr" {
+        value 86;
+        description
+          "ISO 802.5r DTR";
+      }
+      enum "eplrs" {
+        value 87;
+        description
+          "Ext Pos Loc Report Sys";
+      }
+      enum "arap" {
+        value 88;
+        description
+          "Appletalk Remote Access Protocol";
+      }
+      enum "propCnls" {
+        value 89;
+        description
+          "Proprietary Connectionless Protocol";
+      }
+      enum "hostPad" {
+        value 90;
+        description
+          "CCITT-ITU X.29 PAD Protocol";
+      }
+      enum "termPad" {
+        value 91;
+        description
+          "CCITT-ITU X.3 PAD Facility";
+      }
+      enum "frameRelayMPI" {
+        value 92;
+        description
+          "Multiproto Interconnect over FR";
+      }
+      enum "x213" {
+        value 93;
+        description
+          "CCITT-ITU X213";
+      }
+      enum "adsl" {
+        value 94;
+        description
+          "Asymmetric Digital Subscriber Loop";
+      }
+      enum "radsl" {
+        value 95;
+        description
+          "Rate-Adapt. Digital Subscriber Loop";
+      }
+      enum "sdsl" {
+        value 96;
+        description
+          "Symmetric Digital Subscriber Loop";
+      }
+      enum "vdsl" {
+        value 97;
+        description
+          "Very H-Speed Digital Subscrib. Loop";
+      }
+      enum "iso88025CRFPInt" {
+        value 98;
+        description
+          "ISO 802.5 CRFP";
+      }
+      enum "myrinet" {
+        value 99;
+        description
+          "Myricom Myrinet";
+      }
+      enum "voiceEM" {
+        value 100;
+        description
+          "voice recEive and transMit";
+      }
+      enum "voiceFXO" {
+        value 101;
+        description
+          "voice Foreign Exchange Office";
+      }
+      enum "voiceFXS" {
+        value 102;
+        description
+          "voice Foreign Exchange Station";
+      }
+      enum "voiceEncap" {
+        value 103;
+        description
+          "voice encapsulation";
+      }
+      enum "voiceOverIp" {
+        value 104;
+        description
+          "voice over IP encapsulation";
+      }
+      enum "atmDxi" {
+        value 105;
+        description
+          "ATM DXI";
+      }
+      enum "atmFuni" {
+        value 106;
+        description
+          "ATM FUNI";
+      }
+      enum "atmIma" {
+        value 107;
+        description
+          "ATM IMA";
+      }
+      enum "pppMultilinkBundle" {
+        value 108;
+        description
+          "PPP Multilink Bundle";
+      }
+      enum "ipOverCdlc" {
+        value 109;
+        description
+          "IBM ipOverCdlc";
+      }
+      enum "ipOverClaw" {
+        value 110;
+        description
+          "IBM Common Link Access to Workstn";
+      }
+      enum "stackToStack" {
+        value 111;
+        description
+          "IBM stackToStack";
+      }
+      enum "virtualIpAddress" {
+        value 112;
+        description
+          "IBM VIPA";
+      }
+      enum "mpc" {
+        value 113;
+        description
+          "IBM multi-protocol channel support";
+      }
+      enum "ipOverAtm" {
+        value 114;
+        description
+          "IBM ipOverAtm";
+        reference
+          "RFC 2320 - Definitions of Managed Objects for Classical IP
+                      and ARP Over ATM Using SMIv2 (IPOA-MIB)";
+      }
+      enum "iso88025Fiber" {
+        value 115;
+        description
+          "ISO 802.5j Fiber Token Ring";
+      }
+      enum "tdlc" {
+        value 116;
+        description
+          "IBM twinaxial data link control";
+      }
+      enum "gigabitEthernet" {
+        value 117;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635
+           ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "hdlc" {
+        value 118;
+        description
+          "HDLC";
+      }
+      enum "lapf" {
+        value 119;
+        description
+          "LAP F";
+      }
+      enum "v37" {
+        value 120;
+        description
+          "V.37";
+      }
+      enum "x25mlp" {
+        value 121;
+        description
+          "Multi-Link Protocol";
+      }
+      enum "x25huntGroup" {
+        value 122;
+        description
+          "X25 Hunt Group";
+      }
+      enum "transpHdlc" {
+        value 123;
+        description
+          "Transp HDLC";
+      }
+      enum "interleave" {
+        value 124;
+        description
+          "Interleave channel";
+      }
+      enum "fast" {
+        value 125;
+        description
+          "Fast channel";
+      }
+      enum "ip" {
+        value 126;
+        description
+          "IP (for APPN HPR in IP networks)";
+      }
+      enum "docsCableMaclayer" {
+        value 127;
+        description
+          "CATV Mac Layer";
+      }
+      enum "docsCableDownstream" {
+        value 128;
+        description
+          "CATV Downstream interface";
+      }
+      enum "docsCableUpstream" {
+        value 129;
+        description
+          "CATV Upstream interface";
+      }
+      enum "a12MppSwitch" {
+        value 130;
+        description
+          "Avalon Parallel Processor";
+      }
+      enum "tunnel" {
+        value 131;
+        description
+          "Encapsulation interface";
+      }
+      enum "coffee" {
+        value 132;
+        description
+          "coffee pot";
+        reference
+          "RFC 2325 - Coffee MIB";
+      }
+      enum "ces" {
+        value 133;
+        description
+          "Circuit Emulation Service";
+      }
+      enum "atmSubInterface" {
+        value 134;
+        description
+          "ATM Sub Interface";
+      }
+      enum "l2vlan" {
+        value 135;
+        description
+          "Layer 2 Virtual LAN using 802.1Q";
+      }
+      enum "l3ipvlan" {
+        value 136;
+        description
+          "Layer 3 Virtual LAN using IP";
+      }
+      enum "l3ipxvlan" {
+        value 137;
+        description
+          "Layer 3 Virtual LAN using IPX";
+      }
+      enum "digitalPowerline" {
+        value 138;
+        description
+          "IP over Power Lines";
+      }
+      enum "mediaMailOverIp" {
+        value 139;
+        description
+          "Multimedia Mail over IP";
+      }
+      enum "dtm" {
+        value 140;
+        description
+          "Dynamic syncronous Transfer Mode";
+      }
+      enum "dcn" {
+        value 141;
+        description
+          "Data Communications Network";
+      }
+      enum "ipForward" {
+        value 142;
+        description
+          "IP Forwarding Interface";
+      }
+      enum "msdsl" {
+        value 143;
+        description
+          "Multi-rate Symmetric DSL";
+      }
+      enum "ieee1394" {
+        value 144;
+        description
+          "IEEE1394 High Performance Serial Bus";
+      }
+      enum "if-gsn" {
+        value 145;
+        description
+          "HIPPI-6400";
+      }
+      enum "dvbRccMacLayer" {
+        value 146;
+        description
+          "DVB-RCC MAC Layer";
+      }
+      enum "dvbRccDownstream" {
+        value 147;
+        description
+          "DVB-RCC Downstream Channel";
+      }
+      enum "dvbRccUpstream" {
+        value 148;
+        description
+          "DVB-RCC Upstream Channel";
+      }
+      enum "atmVirtual" {
+        value 149;
+        description
+          "ATM Virtual Interface";
+      }
+      enum "mplsTunnel" {
+        value 150;
+        description
+          "MPLS Tunnel Virtual Interface";
+      }
+      enum "srp" {
+        value 151;
+        description
+          "Spatial Reuse Protocol       ";
+      }
+      enum "voiceOverAtm" {
+        value 152;
+        description
+          "Voice Over ATM";
+      }
+      enum "voiceOverFrameRelay" {
+        value 153;
+        description
+          "Voice Over Frame Relay";
+      }
+      enum "idsl" {
+        value 154;
+        description
+          "Digital Subscriber Loop over ISDN";
+      }
+      enum "compositeLink" {
+        value 155;
+        description
+          "Avici Composite Link Interface";
+      }
+      enum "ss7SigLink" {
+        value 156;
+        description
+          "SS7 Signaling Link";
+      }
+      enum "propWirelessP2P" {
+        value 157;
+        description
+          "Prop. P2P wireless interface";
+      }
+      enum "frForward" {
+        value 158;
+        description
+          "Frame Forward Interface";
+      }
+      enum "rfc1483" {
+        value 159;
+        description
+          "Multiprotocol over ATM AAL5";
+        reference
+          "RFC 1483 - Multiprotocol Encapsulation over ATM
+                      Adaptation Layer 5";
+      }
+      enum "usb" {
+        value 160;
+        description
+          "USB Interface";
+      }
+      enum "ieee8023adLag" {
+        value 161;
+        description
+          "IEEE 802.3ad Link Aggregate";
+      }
+      enum "bgppolicyaccounting" {
+        value 162;
+        description
+          "BGP Policy Accounting";
+      }
+      enum "frf16MfrBundle" {
+        value 163;
+        description
+          "FRF .16 Multilink Frame Relay";
+      }
+      enum "h323Gatekeeper" {
+        value 164;
+        description
+          "H323 Gatekeeper";
+      }
+      enum "h323Proxy" {
+        value 165;
+        description
+          "H323 Voice and Video Proxy";
+      }
+      enum "mpls" {
+        value 166;
+        description
+          "MPLS";
+      }
+      enum "mfSigLink" {
+        value 167;
+        description
+          "Multi-frequency signaling link";
+      }
+      enum "hdsl2" {
+        value 168;
+        description
+          "High Bit-Rate DSL - 2nd generation";
+      }
+      enum "shdsl" {
+        value 169;
+        description
+          "Multirate HDSL2";
+      }
+      enum "ds1FDL" {
+        value 170;
+        description
+          "Facility Data Link 4Kbps on a DS1";
+      }
+      enum "pos" {
+        value 171;
+        description
+          "Packet over SONET/SDH Interface";
+      }
+      enum "dvbAsiIn" {
+        value 172;
+        description
+          "DVB-ASI Input";
+      }
+      enum "dvbAsiOut" {
+        value 173;
+        description
+          "DVB-ASI Output";
+      }
+      enum "plc" {
+        value 174;
+        description
+          "Power Line Communtications";
+      }
+      enum "nfas" {
+        value 175;
+        description
+          "Non Facility Associated Signaling";
+      }
+      enum "tr008" {
+        value 176;
+        description
+          "TR008";
+      }
+      enum "gr303RDT" {
+        value 177;
+        description
+          "Remote Digital Terminal";
+      }
+      enum "gr303IDT" {
+        value 178;
+        description
+          "Integrated Digital Terminal";
+      }
+      enum "isup" {
+        value 179;
+        description
+          "ISUP";
+      }
+      enum "propDocsWirelessMaclayer" {
+        value 180;
+        description
+          "Cisco proprietary Maclayer";
+      }
+      enum "propDocsWirelessDownstream" {
+        value 181;
+        description
+          "Cisco proprietary Downstream";
+      }
+      enum "propDocsWirelessUpstream" {
+        value 182;
+        description
+          "Cisco proprietary Upstream";
+      }
+      enum "hiperlan2" {
+        value 183;
+        description
+          "HIPERLAN Type 2 Radio Interface";
+      }
+      enum "propBWAp2Mp" {
+        value 184;
+        description
+          "PropBroadbandWirelessAccesspt2multipt use of this value
+           for IEEE 802.16 WMAN interfaces as per IEEE Std 802.16f
+           is deprecated and ieee80216WMAN(237) should be used
+           instead.";
+      }
+      enum "sonetOverheadChannel" {
+        value 185;
+        description
+          "SONET Overhead Channel";
+      }
+      enum "digitalWrapperOverheadChannel" {
+        value 186;
+        description
+          "Digital Wrapper";
+      }
+      enum "aal2" {
+        value 187;
+        description
+          "ATM adaptation layer 2";
+      }
+      enum "radioMAC" {
+        value 188;
+        description
+          "MAC layer over radio links";
+      }
+      enum "atmRadio" {
+        value 189;
+        description
+          "ATM over radio links";
+      }
+      enum "imt" {
+        value 190;
+        description
+          "Inter Machine Trunks";
+      }
+      enum "mvl" {
+        value 191;
+        description
+          "Multiple Virtual Lines DSL";
+      }
+      enum "reachDSL" {
+        value 192;
+        description
+          "Long Reach DSL";
+      }
+      enum "frDlciEndPt" {
+        value 193;
+        description
+          "Frame Relay DLCI End Point";
+      }
+      enum "atmVciEndPt" {
+        value 194;
+        description
+          "ATM VCI End Point";
+      }
+      enum "opticalChannel" {
+        value 195;
+        description
+          "Optical Channel";
+      }
+      enum "opticalTransport" {
+        value 196;
+        description
+          "Optical Transport";
+      }
+      enum "propAtm" {
+        value 197;
+        description
+          "Proprietary ATM";
+      }
+      enum "voiceOverCable" {
+        value 198;
+        description
+          "Voice Over Cable Interface";
+      }
+      enum "infiniband" {
+        value 199;
+        description
+          "Infiniband";
+      }
+      enum "teLink" {
+        value 200;
+        description
+          "TE Link";
+      }
+      enum "q2931" {
+        value 201;
+        description
+          "Q.2931";
+      }
+      enum "virtualTg" {
+        value 202;
+        description
+          "Virtual Trunk Group";
+      }
+      enum "sipTg" {
+        value 203;
+        description
+          "SIP Trunk Group";
+      }
+      enum "sipSig" {
+        value 204;
+        description
+          "SIP Signaling";
+      }
+      enum "docsCableUpstreamChannel" {
+        value 205;
+        description
+          "CATV Upstream Channel";
+      }
+      enum "econet" {
+        value 206;
+        description
+          "Acorn Econet";
+      }
+      enum "pon155" {
+        value 207;
+        description
+          "FSAN 155Mb Symetrical PON interface";
+      }
+      enum "pon622" {
+        value 208;
+        description
+          "FSAN622Mb Symetrical PON interface";
+      }
+      enum "bridge" {
+        value 209;
+        description
+          "Transparent bridge interface";
+      }
+      enum "linegroup" {
+        value 210;
+        description
+          "Interface common to multiple lines";
+      }
+      enum "voiceEMFGD" {
+        value 211;
+        description
+          "voice E&M Feature Group D";
+      }
+      enum "voiceFGDEANA" {
+        value 212;
+        description
+          "voice FGD Exchange Access North American";
+      }
+      enum "voiceDID" {
+        value 213;
+        description
+          "voice Direct Inward Dialing";
+      }
+      enum "mpegTransport" {
+        value 214;
+        description
+          "MPEG transport interface";
+      }
+      enum "sixToFour" {
+        value 215;
+        status deprecated;
+        description
+          "6to4 interface (DEPRECATED)";
+        reference
+          "RFC 4087 - IP Tunnel MIB";
+      }
+      enum "gtp" {
+        value 216;
+        description
+          "GTP (GPRS Tunneling Protocol)";
+      }
+      enum "pdnEtherLoop1" {
+        value 217;
+        description
+          "Paradyne EtherLoop 1";
+      }
+      enum "pdnEtherLoop2" {
+        value 218;
+        description
+          "Paradyne EtherLoop 2";
+      }
+      enum "opticalChannelGroup" {
+        value 219;
+        description
+          "Optical Channel Group";
+      }
+      enum "homepna" {
+        value 220;
+        description
+          "HomePNA ITU-T G.989";
+      }
+      enum "gfp" {
+        value 221;
+        description
+          "Generic Framing Procedure (GFP)";
+      }
+      enum "ciscoISLvlan" {
+        value 222;
+        description
+          "Layer 2 Virtual LAN using Cisco ISL";
+      }
+      enum "actelisMetaLOOP" {
+        value 223;
+        description
+          "Acteleis proprietary MetaLOOP High Speed Link";
+      }
+      enum "fcipLink" {
+        value 224;
+        description
+          "FCIP Link";
+      }
+      enum "rpr" {
+        value 225;
+        description
+          "Resilient Packet Ring Interface Type";
+      }
+      enum "qam" {
+        value 226;
+        description
+          "RF Qam Interface";
+      }
+      enum "lmp" {
+        value 227;
+        description
+          "Link Management Protocol";
+        reference
+          "RFC 4327 - Link Management Protocol (LMP) Management
+                      Information Base (MIB)";
+      }
+      enum "cblVectaStar" {
+        value 228;
+        description
+          "Cambridge Broadband Networks Limited VectaStar";
+      }
+      enum "docsCableMCmtsDownstream" {
+        value 229;
+        description
+          "CATV Modular CMTS Downstream Interface";
+      }
+      enum "adsl2" {
+        value 230;
+        status deprecated;
+        description
+          "Asymmetric Digital Subscriber Loop Version 2
+           (DEPRECATED/OBSOLETED - please use adsl2plus(238)
+           instead)";
+        reference
+          "RFC 4706 - Definitions of Managed Objects for Asymmetric
+                      Digital Subscriber Line 2 (ADSL2)";
+      }
+      enum "macSecControlledIF" {
+        value 231;
+        description
+          "MACSecControlled";
+      }
+      enum "macSecUncontrolledIF" {
+        value 232;
+        description
+          "MACSecUncontrolled";
+      }
+      enum "aviciOpticalEther" {
+        value 233;
+        description
+         "Avici Optical Ethernet Aggregate";
+      }
+      enum "atmbond" {
+        value 234;
+        description
+          "atmbond";
+      }
+      enum "voiceFGDOS" {
+        value 235;
+        description
+          "voice FGD Operator Services";
+      }
+      enum "mocaVersion1" {
+        value 236;
+        description
+          "MultiMedia over Coax Alliance (MoCA) Interface
+           as documented in information provided privately to IANA";
+      }
+      enum "ieee80216WMAN" {
+        value 237;
+        description
+          "IEEE 802.16 WMAN interface";
+      }
+      enum "adsl2plus" {
+        value 238;
+        description
+          "Asymmetric Digital Subscriber Loop Version 2,
+           Version 2 Plus and all variants";
+      }
+      enum "dvbRcsMacLayer" {
+        value 239;
+        description
+          "DVB-RCS MAC Layer";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "dvbTdm" {
+        value 240;
+        description
+          "DVB Satellite TDM";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "dvbRcsTdma" {
+        value 241;
+        description
+          "DVB-RCS TDMA";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "x86Laps" {
+        value 242;
+        description
+          "LAPS based on ITU-T X.86/Y.1323";
+      }
+      enum "wwanPP" {
+        value 243;
+        description
+          "3GPP WWAN";
+      }
+      enum "wwanPP2" {
+        value 244;
+        description
+          "3GPP2 WWAN";
+      }
+      enum "voiceEBS" {
+        value 245;
+        description
+          "voice P-phone EBS physical interface";
+      }
+      enum "ifPwType" {
+        value 246;
+        description
+          "Pseudowire interface type";
+        reference
+          "RFC 5601 - Pseudowire (PW) Management Information Base";
+      }
+      enum "ilan" {
+        value 247;
+        description
+          "Internal LAN on a bridge per IEEE 802.1ap";
+      }
+      enum "pip" {
+        value 248;
+        description
+          "Provider Instance Port on a bridge per IEEE 802.1ah PBB";
+      }
+      enum "aluELP" {
+        value 249;
+        description
+          "Alcatel-Lucent Ethernet Link Protection";
+      }
+      enum "gpon" {
+        value 250;
+        description
+          "Gigabit-capable passive optical networks (G-PON) as per
+           ITU-T G.948";
+      }
+      enum "vdsl2" {
+        value 251;
+        description
+          "Very high speed digital subscriber line Version 2
+           (as per ITU-T Recommendation G.993.2)";
+        reference
+          "RFC 5650 - Definitions of Managed Objects for Very High
+                      Speed Digital Subscriber Line 2 (VDSL2)";
+      }
+      enum "capwapDot11Profile" {
+        value 252;
+        description
+          "WLAN Profile Interface";
+        reference
+          "RFC 5834 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Binding MIB for
+                      IEEE 802.11";
+      }
+      enum "capwapDot11Bss" {
+        value 253;
+        description
+          "WLAN BSS Interface";
+        reference
+          "RFC 5834 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Binding MIB for
+                      IEEE 802.11";
+      }
+      enum "capwapWtpVirtualRadio" {
+        value 254;
+        description
+          "WTP Virtual Radio Interface";
+        reference
+          "RFC 5833 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Base MIB";
+      }
+      enum "bits" {
+        value 255;
+        description
+          "bitsport";
+      }
+      enum "docsCableUpstreamRfPort" {
+        value 256;
+        description
+          "DOCSIS CATV Upstream RF Port";
+      }
+      enum "cableDownstreamRfPort" {
+        value 257;
+        description
+          "CATV downstream RF port";
+      }
+      enum "vmwareVirtualNic" {
+        value 258;
+        description
+          "VMware Virtual Network Interface";
+      }
+      enum "ieee802154" {
+        value 259;
+        description
+          "IEEE 802.15.4 WPAN interface";
+        reference
+          "IEEE 802.15.4-2006";
+      }
+      enum "otnOdu" {
+        value 260;
+        description
+          "OTN Optical Data Unit";
+      }
+      enum "otnOtu" {
+        value 261;
+        description
+          "OTN Optical channel Transport Unit";
+      }
+      enum "ifVfiType" {
+        value 262;
+        description
+          "VPLS Forwarding Instance Interface Type";
+      }
+      enum "g9981" {
+        value 263;
+        description
+          "G.998.1 bonded interface";
+      }
+      enum "g9982" {
+        value 264;
+        description
+          "G.998.2 bonded interface";
+      }
+      enum "g9983" {
+        value 265;
+        description
+          "G.998.3 bonded interface";
+      }
+      enum "aluEpon" {
+        value 266;
+        description
+          "Ethernet Passive Optical Networks (E-PON)";
+      }
+      enum "aluEponOnu" {
+        value 267;
+        description
+          "EPON Optical Network Unit";
+      }
+      enum "aluEponPhysicalUni" {
+        value 268;
+        description
+          "EPON physical User to Network interface";
+      }
+      enum "aluEponLogicalLink" {
+        value 269;
+        description
+          "The emulation of a point-to-point link over the EPON
+           layer";
+      }
+      enum "aluGponOnu" {
+        value 270;
+        description
+          "GPON Optical Network Unit";
+        reference
+          "ITU-T G.984.2";
+      }
+      enum "aluGponPhysicalUni" {
+        value 271;
+        description
+          "GPON physical User to Network interface";
+        reference
+          "ITU-T G.984.2";
+      }
+      enum "vmwareNicTeam" {
+        value 272;
+        description
+          "VMware NIC Team";
+      }
+    }
+    description
+      "This data type is used as the syntax of the 'type'
+       leaf in the 'interface' list in the YANG module
+       ietf-interface.
+
+       The definition of this typedef with the
+       addition of newly assigned values is published
+       periodically by the IANA, in either the Assigned
+       Numbers RFC, or some derivative of it specific to
+       Internet Network Management number assignments.  (The
+       latest arrangements can be obtained by contacting the
+       IANA.)
+
+       Requests for new values should be made to IANA via
+       email (iana&iana.org).";
+    reference
+      "ifType definitions registry.
+       <http://www.iana.org/assignments/smi-numbers>";
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..de20feb
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang
new file mode 100644 (file)
index 0000000..b9117d0
--- /dev/null
@@ -0,0 +1,565 @@
+module ietf-interfaces {
+
+  namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces";
+  prefix if;
+
+  import ietf-yang-types {
+    prefix yang;
+  }
+  import iana-if-type {
+    prefix ianaift;
+  }
+
+  organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+  contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     WG Chair: Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>
+
+     Editor:   Martin Bjorklund
+               <mailto:mbj@tail-f.com>";
+
+  description
+    "This module contains a collection of YANG definitions for
+     managing network interfaces.
+
+     Copyright (c) 2012 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC XXXX; see
+     the RFC itself for full legal notices.";
+
+  // RFC Ed.: replace XXXX with actual RFC number and remove this
+  // note.
+
+  // RFC Ed.: update the date below with the date of RFC publication
+  // and remove this note.
+  revision 2012-11-15 {
+    description
+      "Initial revision.";
+    reference
+      "RFC XXXX: A YANG Data Model for Interface Management";
+  }
+
+  /* Typedefs */
+
+  typedef interface-ref {
+    type leafref {
+      path "/if:interfaces/if:interface/if:name";
+    }
+    description
+      "This type is used by data models that need to reference
+       interfaces.";
+  }
+
+  /* Features */
+
+  feature arbitrary-names {
+    description
+      "This feature indicates that the server allows interfaces to
+       be named arbitrarily.";
+  }
+
+  feature if-mib {
+    description
+      "This feature indicates that the server implements IF-MIB.";
+    reference
+      "RFC 2863: The Interfaces Group MIB";
+  }
+
+  /* Data nodes */
+
+  container interfaces {
+    description
+      "Interface parameters.";
+
+    list interface {
+      key "name";
+      unique "type location";
+
+      description
+        "The list of interfaces on the device.";
+
+      leaf name {
+        type string;
+        description
+          "The name of the interface.
+
+           A device MAY restrict the allowed values for this leaf,
+           possibly depending on the type and location.
+
+           If the device allows arbitrarily named interfaces, the
+           feature 'arbitrary-names' is advertised.
+
+           This leaf MAY be mapped to ifName by an implementation.
+           Such an implementation MAY restrict the allowed values for
+           this leaf so that it matches the restrictions of ifName.
+           If a NETCONF server that implements this restriction is
+           sent a value that doesn't match the restriction, it MUST
+           reply with an rpc-error with the error-tag
+           'invalid-value'.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifName";
+      }
+
+      leaf description {
+        type string;
+        description
+          "A textual description of the interface.
+
+           This leaf MAY be mapped to ifAlias by an implementation.
+           Such an implementation MAY restrict the allowed values for
+           this leaf so that it matches the restrictions of ifAlias.
+           If a NETCONF server that implements this restriction is
+           sent a value that doesn't match the restriction, it MUST
+           reply with an rpc-error with the error-tag
+           'invalid-value'.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAlias";
+      }
+
+      leaf type {
+        type ianaift:iana-if-type;
+        mandatory true;
+        description
+          "The type of the interface.
+
+           When an interface entry is created, a server MAY
+           initialize the type leaf with a valid value, e.g., if it
+           is possible to derive the type from the name of the
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifType";
+      }
+
+      leaf location {
+        type string;
+        description
+          "The device-specific location of the interface of a
+           particular type.  The format of the location string
+           depends on the interface type and the device.
+
+           If the interface's type represents a physical interface,
+           this leaf MUST be set.
+
+           When an interface entry is created, a server MAY
+           initialize the location leaf with a valid value, e.g., if
+           it is possible to derive the location from the name of
+           the interface.";
+      }
+
+      leaf enabled {
+        type boolean;
+        default "true";
+        description
+          "The desired state of the interface.
+
+           This leaf contains the configured, desired state of the
+           interface.  Systems that implement the IF-MIB use the
+           value of this leaf to set IF-MIB.ifAdminStatus to 'up' or
+           'down' after an ifEntry has been initialized, as described
+           in RFC 2863.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+      }
+
+      leaf oper-status {
+        type enumeration {
+          enum up {
+            value 1;
+            description
+              "Ready to pass packets.";
+          }
+          enum down {
+            value 2;
+            description
+              "The interface does not pass any packets.";
+          }
+          enum testing {
+            value 3;
+            description
+              "In some test mode.  No operational packets can
+               be passed.";
+          }
+          enum unknown {
+            value 4;
+            description
+              "Status cannot be determined for some reason.";
+          }
+          enum dormant {
+            value 5;
+            description
+              "Waiting for some external event.";
+          }
+          enum not-present {
+            value 6;
+            description
+              "Some component is missing.";
+          }
+          enum lower-layer-down {
+            value 7;
+            description
+              "Down due to state of lower-layer interface(s).";
+          }
+        }
+        config false;
+        description
+          "The current operational state of the interface.
+
+           If 'enabled' is 'false' then 'oper-status'
+           should be 'down'.  If 'enabled' is changed to 'true'
+           then 'oper-status' should change to 'up' if the interface
+           is ready to transmit and receive network traffic; it
+           should change to 'dormant' if the interface is waiting for
+           external actions (such as a serial line waiting for an
+           incoming connection); it should remain in the 'down' state
+           if and only if there is a fault that prevents it from
+           going to the 'up' state; it should remain in the
+           'not-present' state if the interface has missing
+           (typically, hardware) components.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifOperStatus";
+      }
+
+      leaf last-change {
+        type yang:date-and-time;
+        config false;
+        description
+          "The time the interface entered its current operational
+           state.  If the current state was entered prior to the
+           last re-initialization of the local network management
+           subsystem, then this node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifLastChange";
+      }
+
+      leaf if-index {
+        if-feature if-mib;
+        type int32 {
+          range "1..2147483647";
+        }
+        config false;
+        description
+          "The ifIndex value for the ifEntry represented by this
+           interface.
+
+           Media-specific modules must specify how the type is
+           mapped to entries in the ifTable.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifIndex";
+      }
+
+      leaf link-up-down-trap-enable {
+        if-feature if-mib;
+        type enumeration {
+          enum enabled {
+            value 1;
+          }
+          enum disabled {
+            value 2;
+          }
+        }
+        description
+          "Indicates whether linkUp/linkDown SNMP notifications
+           should be generated for this interface.
+           If this node is not configured, the value 'enabled' is
+           operationally used by the server for interfaces which do
+           not operate on top of any other interface (i.e., there are
+           no 'lower-layer-if' entries), and 'disabled' otherwise.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifLinkUpDownTrapEnable";
+      }
+
+      leaf phys-address {
+        type yang:phys-address;
+        config false;
+        description
+          "The interface's address at its protocol sub-layer.  For
+          example, for an 802.x interface, this object normally
+          contains a MAC address.  The interface's media-specific
+          modules must define the bit and byte ordering and the
+          format of the value of this object.  For interfaces that do
+          not have such an address (e.g., a serial line), this node
+          is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
+      }
+
+      leaf-list higher-layer-if {
+        type interface-ref;
+        config false;
+        description
+          "A list of references to interfaces layered on top of this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf-list lower-layer-if {
+        type interface-ref;
+        config false;
+        description
+          "A list of references to interfaces layered underneath this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf speed {
+        type yang:gauge64;
+        units "bits / second";
+        config false;
+        description
+            "An estimate of the interface's current bandwidth in bits
+             per second.  For interfaces which do not vary in
+             bandwidth or for those where no accurate estimation can
+             be made, this node should contain the nominal bandwidth.
+             For interfaces that has no concept of bandwidth, this
+             node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifSpeed, ifHighSpeed";
+      }
+
+      container statistics {
+        config false;
+        description
+          "A collection of interface-related statistics objects.";
+
+        leaf discontinuity-time {
+          type yang:date-and-time;
+          description
+            "The time on the most recent occasion at which any one or
+             more of this interface's counters suffered a
+             discontinuity.  If no such discontinuities have occurred
+             since the last re-initialization of the local management
+             subsystem, then this node contains the time the local
+             management subsystem re-initialized itself.";
+        }
+
+        leaf in-octets {
+          type yang:counter64;
+          description
+            "The total number of octets received on the interface,
+             including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
+        }
+        leaf in-unicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were not addressed to a
+             multicast or broadcast address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
+        }
+        leaf in-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were addressed to a broadcast
+             address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInBroadcastPkts";
+        }
+        leaf in-multicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were addressed to a multicast
+             address at this sub-layer.  For a MAC layer protocol,
+             this includes both Group and Functional addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInMulticastPkts";
+        }
+        leaf in-discards {
+          type yang:counter32;
+          description
+            "The number of inbound packets which were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being deliverable to a higher-layer
+             protocol.  One possible reason for discarding such a
+             packet could be to free up buffer space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInDiscards";
+        }
+        leaf in-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of inbound
+             packets that contained errors preventing them from being
+             deliverable to a higher-layer protocol.  For character-
+             oriented or fixed-length interfaces, the number of
+             inbound transmission units that contained errors
+             preventing them from being deliverable to a higher-layer
+             protocol.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInErrors";
+        }
+        leaf in-unknown-protos {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of packets
+             received via the interface which were discarded because
+             of an unknown or unsupported protocol.  For
+             character-oriented or fixed-length interfaces that
+             support protocol multiplexing the number of transmission
+             units received via the interface which were discarded
+             because of an unknown or unsupported protocol.  For any
+             interface that does not support protocol multiplexing,
+             this counter is not present.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
+        }
+
+        leaf out-octets {
+          type yang:counter64;
+          description
+            "The total number of octets transmitted out of the
+             interface, including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
+        }
+        leaf out-unicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were not addressed
+             to a multicast or broadcast address at this sub-layer,
+             including those that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
+        }
+        leaf out-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were addressed to a
+             broadcast address at this sub-layer, including those
+             that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutBroadcastPkts";
+        }
+        leaf out-multicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were addressed to a
+             multicast address at this sub-layer, including those
+             that were discarded or not sent.  For a MAC layer
+             protocol, this includes both Group and Functional
+             addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutMulticastPkts";
+        }
+        leaf out-discards {
+          type yang:counter32;
+          description
+            "The number of outbound packets which were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being transmitted.  One possible reason
+             for discarding such a packet could be to free up buffer
+             space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
+        }
+        leaf out-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of outbound
+             packets that could not be transmitted because of errors.
+             For character-oriented or fixed-length interfaces, the
+             number of outbound transmission units that could not be
+             transmitted because of errors.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutErrors";
+        }
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..e9d88ab
--- /dev/null
@@ -0,0 +1,396 @@
+ module ietf-yang-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-yang-types";
+   prefix "yang";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of counter and gauge types ***/
+
+   typedef counter32 {
+     type uint32;
+     description
+      "The counter32 type represents a non-negative integer
+       that monotonically increases until it reaches a
+       maximum value of 2^32-1 (4294967295 decimal), when it
+       wraps around and starts increasing again from zero.
+
+       Counters have no defined 'initial' value, and thus, a
+       single value of a counter has (in general) no information
+       content.  Discontinuities in the monotonically increasing
+       value normally occur at re-initialization of the
+       management system, and at other times as specified in the
+       description of a schema node using this type.  If such
+       other times can occur, for example, the creation of
+       a schema node of type counter32 at times other than
+       re-initialization, then a corresponding schema node
+       should be defined, with an appropriate type, to indicate
+       the last discontinuity.
+
+       The counter32 type should not be used for configuration
+       schema nodes.  A default statement SHOULD NOT be used in
+       combination with the type counter32.
+
+       In the value set and its semantics, this type is equivalent
+       to the Counter32 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef zero-based-counter32 {
+     type yang:counter32;
+     default "0";
+     description
+      "The zero-based-counter32 type represents a counter32
+       that has the defined 'initial' value zero.
+
+       A schema node of this type will be set to zero (0) on creation
+       and will thereafter increase monotonically until it reaches
+       a maximum value of 2^32-1 (4294967295 decimal), when it
+       wraps around and starts increasing again from zero.
+
+       Provided that an application discovers a new schema node
+       of this type within the minimum time to wrap, it can use the
+       'initial' value as a delta.  It is important for a management
+       station to be aware of this minimum time and the actual time
+       between polls, and to discard data if the actual time is too
+       long or there is no defined minimum time.
+
+       In the value set and its semantics, this type is equivalent
+       to the ZeroBasedCounter32 textual convention of the SMIv2.";
+     reference
+       "RFC 4502: Remote Network Monitoring Management Information
+                  Base Version 2";
+   }
+
+   typedef counter64 {
+     type uint64;
+     description
+      "The counter64 type represents a non-negative integer
+       that monotonically increases until it reaches a
+       maximum value of 2^64-1 (18446744073709551615 decimal),
+       when it wraps around and starts increasing again from zero.
+
+       Counters have no defined 'initial' value, and thus, a
+       single value of a counter has (in general) no information
+       content.  Discontinuities in the monotonically increasing
+       value normally occur at re-initialization of the
+       management system, and at other times as specified in the
+       description of a schema node using this type.  If such
+       other times can occur, for example, the creation of
+       a schema node of type counter64 at times other than
+       re-initialization, then a corresponding schema node
+       should be defined, with an appropriate type, to indicate
+       the last discontinuity.
+
+       The counter64 type should not be used for configuration
+       schema nodes.  A default statement SHOULD NOT be used in
+       combination with the type counter64.
+
+       In the value set and its semantics, this type is equivalent
+       to the Counter64 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef zero-based-counter64 {
+     type yang:counter64;
+     default "0";
+     description
+      "The zero-based-counter64 type represents a counter64 that
+       has the defined 'initial' value zero.
+
+       A schema node of this type will be set to zero (0) on creation
+       and will thereafter increase monotonically until it reaches
+       a maximum value of 2^64-1 (18446744073709551615 decimal),
+       when it wraps around and starts increasing again from zero.
+
+       Provided that an application discovers a new schema node
+       of this type within the minimum time to wrap, it can use the
+       'initial' value as a delta.  It is important for a management
+       station to be aware of this minimum time and the actual time
+       between polls, and to discard data if the actual time is too
+       long or there is no defined minimum time.
+
+       In the value set and its semantics, this type is equivalent
+       to the ZeroBasedCounter64 textual convention of the SMIv2.";
+     reference
+      "RFC 2856: Textual Conventions for Additional High Capacity
+                 Data Types";
+   }
+
+   typedef gauge32 {
+     type uint32;
+     description
+      "The gauge32 type represents a non-negative integer, which
+       may increase or decrease, but shall never exceed a maximum
+       value, nor fall below a minimum value.  The maximum value
+       cannot be greater than 2^32-1 (4294967295 decimal), and
+       the minimum value cannot be smaller than 0.  The value of
+       a gauge32 has its maximum value whenever the information
+       being modeled is greater than or equal to its maximum
+       value, and has its minimum value whenever the information
+       being modeled is smaller than or equal to its minimum value.
+       If the information being modeled subsequently decreases
+       below (increases above) the maximum (minimum) value, the
+       gauge32 also decreases (increases).
+
+       In the value set and its semantics, this type is equivalent
+       to the Gauge32 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef gauge64 {
+     type uint64;
+     description
+      "The gauge64 type represents a non-negative integer, which
+       may increase or decrease, but shall never exceed a maximum
+       value, nor fall below a minimum value.  The maximum value
+       cannot be greater than 2^64-1 (18446744073709551615), and
+       the minimum value cannot be smaller than 0.  The value of
+       a gauge64 has its maximum value whenever the information
+       being modeled is greater than or equal to its maximum
+       value, and has its minimum value whenever the information
+       being modeled is smaller than or equal to its minimum value.
+       If the information being modeled subsequently decreases
+       below (increases above) the maximum (minimum) value, the
+       gauge64 also decreases (increases).
+
+       In the value set and its semantics, this type is equivalent
+       to the CounterBasedGauge64 SMIv2 textual convention defined
+       in RFC 2856";
+     reference
+      "RFC 2856: Textual Conventions for Additional High Capacity
+                 Data Types";
+   }
+
+   /*** collection of identifier related types ***/
+
+   typedef object-identifier {
+     type string {
+       pattern '(([0-1](\.[1-3]?[0-9]))|(2\.(0|([1-9]\d*))))'
+             + '(\.(0|([1-9]\d*)))*';
+     }
+     description
+      "The object-identifier type represents administratively
+       assigned names in a registration-hierarchical-name tree.
+
+       Values of this type are denoted as a sequence of numerical
+       non-negative sub-identifier values.  Each sub-identifier
+       value MUST NOT exceed 2^32-1 (4294967295).  Sub-identifiers
+       are separated by single dots and without any intermediate
+       whitespace.
+
+       The ASN.1 standard restricts the value space of the first
+       sub-identifier to 0, 1, or 2.  Furthermore, the value space
+       of the second sub-identifier is restricted to the range
+       0 to 39 if the first sub-identifier is 0 or 1.  Finally,
+       the ASN.1 standard requires that an object identifier
+       has always at least two sub-identifier.  The pattern
+       captures these restrictions.
+
+       Although the number of sub-identifiers is not limited,
+       module designers should realize that there may be
+       implementations that stick with the SMIv2 limit of 128
+       sub-identifiers.
+
+       This type is a superset of the SMIv2 OBJECT IDENTIFIER type
+       since it is not restricted to 128 sub-identifiers.  Hence,
+       this type SHOULD NOT be used to represent the SMIv2 OBJECT
+       IDENTIFIER type, the object-identifier-128 type SHOULD be
+       used instead.";
+     reference
+      "ISO9834-1: Information technology -- Open Systems
+       Interconnection -- Procedures for the operation of OSI
+       Registration Authorities: General procedures and top
+       arcs of the ASN.1 Object Identifier tree";
+   }
+
+
+
+
+   typedef object-identifier-128 {
+     type object-identifier {
+       pattern '\d*(\.\d*){1,127}';
+     }
+     description
+      "This type represents object-identifiers restricted to 128
+       sub-identifiers.
+
+       In the value set and its semantics, this type is equivalent
+       to the OBJECT IDENTIFIER type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   /*** collection of date and time related types ***/
+
+   typedef date-and-time {
+     type string {
+       pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?'
+             + '(Z|[\+\-]\d{2}:\d{2})';
+     }
+     description
+      "The date-and-time type is a profile of the ISO 8601
+       standard for representation of dates and times using the
+       Gregorian calendar.  The profile is defined by the
+       date-time production in Section 5.6 of RFC 3339.
+
+       The date-and-time type is compatible with the dateTime XML
+       schema type with the following notable exceptions:
+
+       (a) The date-and-time type does not allow negative years.
+
+       (b) The date-and-time time-offset -00:00 indicates an unknown
+           time zone (see RFC 3339) while -00:00 and +00:00 and Z all
+           represent the same time zone in dateTime.
+
+       (c) The canonical format (see below) of data-and-time values
+           differs from the canonical format used by the dateTime XML
+           schema type, which requires all times to be in UTC using the
+           time-offset 'Z'.
+
+       This type is not equivalent to the DateAndTime textual
+       convention of the SMIv2 since RFC 3339 uses a different
+       separator between full-date and full-time and provides
+       higher resolution of time-secfrac.
+
+       The canonical format for date-and-time values with a known time
+       zone uses a numeric time zone offset that is calculated using
+       the device's configured known offset to UTC time.  A change of
+       the device's offset to UTC time will cause date-and-time values
+       to change accordingly.  Such changes might happen periodically
+       in case a server follows automatically daylight saving time
+       (DST) time zone offset changes.  The canonical format for
+       date-and-time values with an unknown time zone (usually referring
+       to the notion of local time) uses the time-offset -00:00.";
+     reference
+      "RFC 3339: Date and Time on the Internet: Timestamps
+       RFC 2579: Textual Conventions for SMIv2
+       XSD-TYPES: XML Schema Part 2: Datatypes Second Edition";
+   }
+
+   typedef timeticks {
+     type uint32;
+     description
+      "The timeticks type represents a non-negative integer that
+       represents the time, modulo 2^32 (4294967296 decimal), in
+       hundredths of a second between two epochs.  When a schema
+       node is defined that uses this type, the description of
+       the schema node identifies both of the reference epochs.
+
+       In the value set and its semantics, this type is equivalent
+       to the TimeTicks type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef timestamp {
+     type yang:timeticks;
+     description
+      "The timestamp type represents the value of an associated
+       timeticks schema node at which a specific occurrence happened.
+       The specific occurrence must be defined in the description
+       of any schema node defined using this type.  When the specific
+       occurrence occurred prior to the last time the associated
+       timeticks attribute was zero, then the timestamp value is
+       zero.  Note that this requires all timestamp values to be
+       reset to zero when the value of the associated timeticks
+       attribute reaches 497+ days and wraps around to zero.
+
+       The associated timeticks schema node must be specified
+       in the description of any schema node using this type.
+
+       In the value set and its semantics, this type is equivalent
+       to the TimeStamp textual convention of the SMIv2.";
+     reference
+      "RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   /*** collection of generic address types ***/
+
+   typedef phys-address {
+     type string {
+       pattern '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*)?';
+     }
+     description
+      "Represents media- or physical-level addresses represented
+       as a sequence octets, each octet represented by two hexadecimal
+       numbers.  Octets are separated by colons.  The canonical
+       representation uses lowercase characters.
+
+       In the value set and its semantics, this type is equivalent
+       to the PhysAddress textual convention of the SMIv2.";
+     reference
+      "RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   typedef mac-address {
+     type string {
+       pattern '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}';
+     }
+     description
+      "The mac-address type represents an IEEE 802 MAC address.
+       The canonical representation uses lowercase characters.
+
+       In the value set and its semantics, this type is equivalent
+       to the MacAddress textual convention of the SMIv2.";
+     reference
+      "IEEE 802: IEEE Standard for Local and Metropolitan Area
+                 Networks: Overview and Architecture
+       RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   /*** collection of XML specific types ***/
+
+   typedef xpath1.0 {
+     type string;
+     description
+      "This type represents an XPATH 1.0 expression.
+
+       When a schema node is defined that uses this type, the
+       description of the schema node MUST specify the XPath
+       context in which the XPath expression is evaluated.";
+     reference
+      "XPATH: XML Path Language (XPath) Version 1.0";
+   }
+
+ }
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang
new file mode 100644 (file)
index 0000000..f0cb123
--- /dev/null
@@ -0,0 +1,57 @@
+module binary-type-test {
+    yang-version 1;
+    namespace "urn:binary:types:model";
+    prefix "btt";
+
+    import binary-types {
+        prefix "bin";
+        revision-date 2013-06-13;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "Simple test to test imported binary types and resolving of binary
+        type in leaf statement.";
+
+    revision "2013-06-13" {
+        reference "NO REF";
+    }
+
+    typedef binary-type {
+        type binary {
+            length 128;
+        }
+    }
+
+    container container-foo {
+        leaf binary-leaf {
+            type binary {
+                length 128;
+            }
+        }
+
+        list binary-list {
+            key "binary-key";
+
+            leaf binary-key {
+                type btt:binary-type;
+            }
+
+            leaf imported-simple-binary {
+                type bin:simple-binary;
+            }
+        }
+
+        leaf imported-restrict-binary {
+            type bin:restricted-binary;
+        }
+
+        leaf-list binary-list {
+            type binary {
+                length 256;
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang
new file mode 100644 (file)
index 0000000..df55441
--- /dev/null
@@ -0,0 +1,38 @@
+ module binary-types {
+
+   namespace "urn:binary:types";
+   prefix "bin";
+
+   organization "OPEN DAYLIGHT";
+
+   contact "http://www.opendaylight.org/";
+
+   description "Stand alone binary types declaration file for testing
+   purposes only.";
+
+   revision 2013-06-13 {
+     description
+      "Initial revision.";
+     reference
+      "NO REFERENCE";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef simple-binary {
+     type binary;
+   }
+
+   typedef restricted-binary {
+     type binary {
+        length 24;
+     }
+   }
+
+   typedef composite-binary {
+     type union {
+        type bin:simple-binary;
+        type bin:restricted-binary;
+     }
+   }
+ }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang
new file mode 100644 (file)
index 0000000..d4a7341
--- /dev/null
@@ -0,0 +1,153 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types {
+        prefix "inet";
+        revision-date 2010-09-24;
+    }
+
+    import ietf-interfaces {
+        prefix "if";
+        revision-date 2012-11-15;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    revision "2013-01-01" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    typedef interface-id-ref {
+        type leafref {
+            path "/tp:topology/tp:interfaces/tp:interface/tp:interface-id";
+        }
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+
+        container interfaces {
+            list interface {
+                key "interface-id";
+
+                leaf interface-id {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:name";
+                    }
+                }
+
+                leaf-list higher-layer-if {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:higher-layer-if";
+                    }
+                }
+
+                leaf oper-status {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:oper-status";
+                    }
+                }
+
+                leaf link-up-down-trap-enable {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:link-up-down-trap-enable";
+                    }
+                }
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container tunnels {
+                    list tunnel {
+                        key "tunnel-id";
+
+                        leaf tunnel-id {
+                            type leafref {
+                                path "../../../link-id";
+                            }
+                        }
+                    }
+                }
+
+                leaf interface {
+                    type interface-id-ref;
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..6a6c748
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang
new file mode 100644 (file)
index 0000000..a4b589b
--- /dev/null
@@ -0,0 +1,120 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types { 
+        prefix "inet"; 
+        revision-date 2010-09-24;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    revision "2013-01-01" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+
+    typedef union-enum {
+        type union {
+            type int32;
+            type enumeration {
+                enum "unbounded";
+            }
+        }
+    }
+
+    typedef link-address {
+        type union {
+            type inet:ip-address;
+            type string;
+        }
+    }
+
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                leaf bounding {
+                    type union-enum;
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                leaf link-address {
+                    type link-address;
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..6a6c748
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
\ No newline at end of file
index 3c00dee98ea30e95cb4547ffbb1b29cc5f2386f0..93be5a667ca23307002dc7ad73ff1234a94a91a8 100644 (file)
@@ -15,5 +15,21 @@ public interface TypeProvider {
     @Deprecated\r
     Type javaTypeForYangType(String type);\r
 \r
+    /**\r
+     * Resolve of yang Type Definition to it's java counter part.\r
+     * If the Type Definition contains one of yang primitive types the method\r
+     * will return java.lang. counterpart. (For example if yang type is int32\r
+     * the java counterpart is java.lang.Integer). In case that Type\r
+     * Definition contains extended type defined via yang typedef statement\r
+     * the method SHOULD return Generated Type or Generated Transfer Object\r
+     * if that Type is correctly referenced to resolved imported yang module.\r
+     * The method will return <cdoe>null</cdoe> value in situations that\r
+     * TypeDefinition can't be resolved (either due missing yang import or\r
+     * incorrectly specified type).\r
+     *\r
+     *\r
+     * @param type Type Definition to resolve from\r
+     * @return Resolved Type\r
+     */\r
     Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type);\r
 }\r
index 6683230d028ef8c419b05413d0828a31fc84f772..a9d1cf5227c4efb575debadfb52eb288f64032b7 100644 (file)
@@ -63,7 +63,9 @@ public class AbstractBaseType implements Type {
 \r
     @Override\r
     public String toString() {\r
-\r
+        if (packageName.isEmpty()) {\r
+            return "Type (" + name + ")";\r
+        }\r
         return "Type (" + packageName + "." + name + ")";\r
     }\r
 \r
index 1fb862291f19700b673a153112bf6f4352d02553..ef65a0e8f03add4a1653406c6069ed18e6c3f148 100644 (file)
@@ -3,11 +3,14 @@ package org.opendaylight.controller.binding.generator.util;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.controller.yang.common.QName;
-import org.opendaylight.controller.yang.model.api.*;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaNode;
+import org.opendaylight.controller.yang.model.api.SchemaPath;
+import org.opendaylight.controller.yang.model.api.TypeDefinition;
 
 import java.util.*;
 
-public class BindingGeneratorUtil {
+public final class BindingGeneratorUtil {
 
     private static final String[] SET_VALUES = new String[]{"abstract",
             "assert", "boolean", "break", "byte", "case", "catch", "char",
@@ -19,7 +22,8 @@ public class BindingGeneratorUtil {
             "super", "switch", "synchronized", "this", "throw", "throws",
             "transient", "true", "try", "void", "volatile", "while"};
 
-    private BindingGeneratorUtil() {}
+    private BindingGeneratorUtil() {
+    }
 
     public static final Set<String> JAVA_RESERVED_WORDS = new HashSet<String>(
             Arrays.asList(SET_VALUES));
@@ -110,22 +114,43 @@ public class BindingGeneratorUtil {
 
     public static String packageNameForGeneratedType(
             final String basePackageName, final SchemaPath schemaPath) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (schemaPath == null) {
+            throw new IllegalArgumentException("Schema Path cannot be NULL!");
+        }
+
         final StringBuilder builder = new StringBuilder();
         builder.append(basePackageName);
-        if ((schemaPath != null) && (schemaPath.getPath() != null)) {
-            final List<QName> pathToNode = schemaPath.getPath();
-            final int traversalSteps = (pathToNode.size() - 1);
-            for (int i = 0; i < traversalSteps; ++i) {
-                builder.append(".");
-                String nodeLocalName = pathToNode.get(i).getLocalName();
-
-                nodeLocalName = nodeLocalName.replace(":", ".");
-                nodeLocalName = nodeLocalName.replace("-", ".");
-                builder.append(nodeLocalName);
-            }
-            return validateJavaPackage(builder.toString());
+        final List<QName> pathToNode = schemaPath.getPath();
+        final int traversalSteps = (pathToNode.size() - 1);
+        for (int i = 0; i < traversalSteps; ++i) {
+            builder.append(".");
+            String nodeLocalName = pathToNode.get(i).getLocalName();
+
+            nodeLocalName = nodeLocalName.replace(":", ".");
+            nodeLocalName = nodeLocalName.replace("-", ".");
+            builder.append(nodeLocalName);
         }
-        return null;
+        return validateJavaPackage(builder.toString());
+    }
+
+    public static String packageNameForTypeDefinition(
+            final String basePackageName, final TypeDefinition<?> typeDefinition) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition reference " +
+                    "cannot be NULL!");
+        }
+
+        final StringBuilder builder = new StringBuilder();
+        builder.append(basePackageName);
+        return validateJavaPackage(builder.toString());
     }
 
     public static String parseToClassName(String token) {
index 87bb47cb76e6819f9b93fd0180154b4545c25bd8..26be94351c67b9db724d7fd27a44abfbf26c9051 100644 (file)
@@ -18,21 +18,22 @@ import org.opendaylight.controller.yang.binding.Augmentable;
 import org.opendaylight.controller.yang.binding.Augmentation;\r
 import org.opendaylight.controller.yang.binding.DataObject;\r
 \r
-public class Types {\r
+public final class Types {\r
     private static final Type SET_TYPE = typeForClass(Set.class);\r
     private static final Type LIST_TYPE = typeForClass(List.class);\r
     private static final Type MAP_TYPE = typeForClass(Map.class);\r
-    \r
     public static final Type DATA_OBJECT = typeForClass(DataObject.class);\r
-    \r
-    private Types() {\r
-    }\r
 \r
     public static ConcreteType voidType() {\r
         return new ConcreteTypeImpl(Void.class.getPackage().getName(),\r
                 Void.class.getSimpleName());\r
     }\r
 \r
+    public static final Type primitiveType(final String primitiveType) {\r
+        return new ConcreteTypeImpl("", primitiveType);\r
+    }\r
+\r
+\r
     /**\r
      * Returns an instance of {@link ConcreteType} describing the class\r
      * \r
index 01d9bbfa9fb05550d0e497df74fd89c0f52ba5c7..558fb438504eda14a3c64b1b793f71f3f0a28e60 100644 (file)
@@ -101,7 +101,8 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
     
     @Override
     public EnumBuilder addEnumeration(String name) {
-        final EnumBuilder builder = new EnumerationBuilderImpl(packageName,
+        final String innerPackageName = packageName + "." + this.name;
+        final EnumBuilder builder = new EnumerationBuilderImpl(innerPackageName,
                 name);
         enumerations.add(builder);
         return builder;
index 942174fdcede1485b1c931133400d945f70787c6..0dcaa71c139be25d46bdaa250d07e9270dc13dd5 100644 (file)
@@ -17,11 +17,12 @@ import java.util.List;
 import java.util.Map;
 
 import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public class ClassCodeGenerator implements CodeGenerator {
+public final class ClassCodeGenerator implements CodeGenerator {
 
     private Map<String, LinkedHashMap<String, Integer>> imports;
 
@@ -29,11 +30,12 @@ public class ClassCodeGenerator implements CodeGenerator {
     public Writer generate(Type type) throws IOException {
         final Writer writer = new StringWriter();
         if (type instanceof GeneratedTransferObject) {
-            GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+            GeneratedTransferObject genTO = (GeneratedTransferObject) type;            
             imports = GeneratorUtil.createImports(genTO);
-
+            
             final String currentPkg = genTO.getPackageName();
             final List<GeneratedProperty> fields = genTO.getProperties();
+            final List<Enumeration> enums = genTO.getEnumDefintions();
 
             writer.write(GeneratorUtil.createPackageDeclaration(currentPkg));
             writer.write(NL);
@@ -48,6 +50,14 @@ public class ClassCodeGenerator implements CodeGenerator {
                     imports));
             writer.write(NL);
             writer.write(NL);
+            
+            if (enums != null) {           
+                       EnumGenerator enumGenerator = new EnumGenerator();
+               for ( Enumeration e : enums ) {                         
+                       writer.write(enumGenerator.generateInnerEnumeration(e, TAB).toString());
+                       writer.write(NL);
+               }
+            }
 
             if (fields != null) {
                 for (GeneratedProperty field : fields) {
index fbbd54e2023c56e3e009dcdd9c6e9ec277021395..bd94c20ffb5b3bbdc5aaf06905771d2e18d9aa24 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.controller.sal.java.api.generator;
 
-public class Constants {
+final class Constants {
 
     public static final String IFC = "interface";
     public static final String CLASS = "class";
@@ -32,4 +32,9 @@ public class Constants {
     public static final String FINAL = "final";
     public static final String EXTENDS = "extends";
     public static final String IMPLEMENTS = "implements";
+    
+    public static final String ENUMERATION_NAME = "value";
+    public static final String ENUMERATION_TYPE = "int";       
+    
+    private Constants() {}
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java b/opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java
new file mode 100644 (file)
index 0000000..33d2917
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.java.api.generator;
+
+import static org.opendaylight.controller.sal.java.api.generator.Constants.*;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+public class EnumGenerator implements CodeGenerator {
+
+       @Override
+       public Writer generate(Type type) throws IOException {
+               final Writer writer = new StringWriter();
+
+               if (type instanceof Enumeration) {
+                       Enumeration enums = (Enumeration) type;
+                       writer.write(GeneratorUtil.createPackageDeclaration(enums
+                                       .getPackageName()));
+                       writer.write(NL + NL);
+                       writer.write(GeneratorUtil.createEnum(enums, ""));
+               }
+
+               return writer;
+       }
+
+       public Writer generateInnerEnumeration(Type type, String indent) throws IOException {
+               final Writer writer = new StringWriter();
+
+               if (type instanceof Enumeration) {
+                       Enumeration enums = (Enumeration) type;
+                       writer.write(GeneratorUtil.createEnum(enums, indent));
+               }
+
+               return writer;
+       }
+
+}
index a0db8c7b6d500d7b7ea1b420c43a7456c2081a97..ab103b471e8fc076609308078aa1bba98b3f3a11 100644 (file)
@@ -18,35 +18,45 @@ import java.util.List;
 import java.util.Set;
 
 import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class GeneratorJavaFile {
+public final class GeneratorJavaFile {
 
     private static final Logger log = LoggerFactory
             .getLogger(GeneratorJavaFile.class);
     private final CodeGenerator interfaceGenerator;
     private final ClassCodeGenerator classGenerator;
+    private final EnumGenerator enumGenerator;
+    
     private final Set<GeneratedType> genTypes;
     private final Set<GeneratedTransferObject> genTransferObjects;
+    private final Set<Enumeration> enumerations; 
 
     public GeneratorJavaFile(final CodeGenerator codeGenerator,
             final Set<GeneratedType> types) {
         this.interfaceGenerator = codeGenerator;
         this.genTypes = types;
         this.genTransferObjects = new HashSet<>();
-        classGenerator = new ClassCodeGenerator();
+        this.enumerations = new HashSet<>();
+        this.classGenerator = new ClassCodeGenerator();
+        this.enumGenerator = new EnumGenerator();
     }
 
     public GeneratorJavaFile(final Set<GeneratedType> types,
-            final Set<GeneratedTransferObject> genTransferObjects) {
+            final Set<GeneratedTransferObject> genTransferObjects,
+            final Set<Enumeration> enumerations) {
         this.interfaceGenerator = new InterfaceGenerator();
         this.classGenerator = new ClassCodeGenerator();
+        this.enumGenerator = new EnumGenerator();
+        
         this.genTypes = types;
         this.genTransferObjects = genTransferObjects;
+        this.enumerations = enumerations;
     }
 
     public List<File> generateToFile(final File parentDirectory) throws IOException {
@@ -67,6 +77,16 @@ public class GeneratorJavaFile {
                 result.add(genFile);
             }
         }
+        
+        for (Enumeration enumeration : enumerations) {
+            final File genFile = generateTypeToJavaFile(parentDirectory,
+                    enumeration, enumGenerator);
+
+            if (genFile != null) {
+                result.add(genFile);
+            }
+        }
+        
         return result;
     }
 
index b85e2b0ed7ed78f1a43c23a2bf207f8c56df5b0e..bb4bbbaf789191e29ff6e87a446595f84ee5bd5c 100644 (file)
@@ -27,646 +27,669 @@ import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Paramet
 import org.opendaylight.controller.sal.binding.model.api.ParameterizedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public class GeneratorUtil {
-
-    private GeneratorUtil() {
-    }
-
-    public static String createIfcDeclaration(final GeneratedType genType,
-            final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports) {
-        return createFileDeclaration(IFC, genType, indent, availableImports);
-    }
-
-    public static String createClassDeclaration(
-            final GeneratedTransferObject genTransferObject,
-            final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports) {
-        return createFileDeclaration(CLASS, genTransferObject, indent,
-                availableImports);
-    }
-
-    public static String createPackageDeclaration(final String packageName) {
-        return PKG + GAP + packageName + SC;
-    }
-
-    private static String createFileDeclaration(final String type,
-            final GeneratedType genType, final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports) {
-        final StringBuilder builder = new StringBuilder();
-        final String currentPkg = genType.getPackageName();
-
-        createComment(builder, genType.getComment(), indent);
-
-        if (!genType.getAnnotations().isEmpty()) {
-            final List<AnnotationType> annotations = genType.getAnnotations();
-            appendAnnotations(builder, annotations);
-            builder.append(NL);
-        }
-        builder.append(PUBLIC + GAP + type + GAP + genType.getName() + GAP);
-
-        if (genType instanceof GeneratedTransferObject) {
-            GeneratedTransferObject genTO = (GeneratedTransferObject) genType;
-
-            if (genTO.getExtends() != null) {
-                builder.append(EXTENDS + GAP);
-                builder.append(genTO.getExtends() + GAP);
-            }
-        }
-
-        final List<Type> genImplements = genType.getImplements();
-        if (!genImplements.isEmpty()) {
-            if (genType instanceof GeneratedTransferObject) {
-                builder.append(IMPLEMENTS + GAP);
-            } else {
-                builder.append(EXTENDS + GAP);
-            }
-            builder.append(getExplicitType(genImplements.get(0),
-                    availableImports, currentPkg));
-
-            for (int i = 1; i < genImplements.size(); ++i) {
-                builder.append(", ");
-                builder.append(getExplicitType(genImplements.get(i),
-                        availableImports, currentPkg));
-            }
-        }
-
-        builder.append(GAP + LCB);
-        return builder.toString();
-    }
-
-    private static StringBuilder appendAnnotations(final StringBuilder builder,
-            final List<AnnotationType> annotations) {
-        if ((builder != null) && (annotations != null)) {
-            for (final AnnotationType annotation : annotations) {
-                builder.append("@");
-                builder.append(annotation.getPackageName());
-                builder.append(".");
-                builder.append(annotation.getName());
-
-                if (annotation.containsParameters()) {
-                    builder.append("(");
-                    final List<AnnotationType.Parameter> parameters = annotation
-                            .getParameters();
-                    appendAnnotationParams(builder, parameters);
-                    builder.append(")");
-                }
-            }
-        }
-        return builder;
-    }
-
-    private static StringBuilder appendAnnotationParams(
-            final StringBuilder builder,
-            final List<AnnotationType.Parameter> parameters) {
-        if (parameters != null) {
-            int i = 0;
-            for (final AnnotationType.Parameter param : parameters) {
-                if (param == null) {
-                    continue;
-                }
-                if (i > 0) {
-                    builder.append(", ");
-                }
-                final String paramName = param.getName();
-                if (param.getValue() != null) {
-                    builder.append(paramName);
-                    builder.append(" = ");
-                    builder.append(param.getValue());
+public final class GeneratorUtil {
+
+       private GeneratorUtil() {
+       }
+
+       public static String createIfcDeclaration(final GeneratedType genType,
+                       final String indent,
+                       final Map<String, LinkedHashMap<String, Integer>> availableImports) {
+               return createFileDeclaration(IFC, genType, indent, availableImports);
+       }
+
+       public static String createClassDeclaration(
+                       final GeneratedTransferObject genTransferObject,
+                       final String indent,
+                       final Map<String, LinkedHashMap<String, Integer>> availableImports) {
+               return createFileDeclaration(CLASS, genTransferObject, indent,
+                               availableImports);
+       }
+
+       public static String createPackageDeclaration(final String packageName) {
+               return PKG + GAP + packageName + SC;
+       }
+
+       private static String createFileDeclaration(final String type,
+                       final GeneratedType genType, final String indent,
+                       final Map<String, LinkedHashMap<String, Integer>> availableImports) {
+               final StringBuilder builder = new StringBuilder();
+               final String currentPkg = genType.getPackageName();
+
+               createComment(builder, genType.getComment(), indent);
+
+               if (!genType.getAnnotations().isEmpty()) {
+                       final List<AnnotationType> annotations = genType.getAnnotations();
+                       appendAnnotations(builder, annotations);
+                       builder.append(NL);
+               }
+               builder.append(PUBLIC + GAP + type + GAP + genType.getName() + GAP);
+
+               if (genType instanceof GeneratedTransferObject) {
+                       GeneratedTransferObject genTO = (GeneratedTransferObject) genType;
+
+                       if (genTO.getExtends() != null) {
+                               builder.append(EXTENDS + GAP);
+                               builder.append(genTO.getExtends() + GAP);
+                       }
+               }
+
+               final List<Type> genImplements = genType.getImplements();
+               if (!genImplements.isEmpty()) {
+                       if (genType instanceof GeneratedTransferObject) {
+                               builder.append(IMPLEMENTS + GAP);
+                       } else {
+                               builder.append(EXTENDS + GAP);
+                       }
+                       builder.append(getExplicitType(genImplements.get(0),
+                                       availableImports, currentPkg));
+
+                       for (int i = 1; i < genImplements.size(); ++i) {
+                               builder.append(", ");
+                               builder.append(getExplicitType(genImplements.get(i),
+                                               availableImports, currentPkg));
+                       }
+               }
+
+               builder.append(GAP + LCB);
+               return builder.toString();
+       }
+
+       private static StringBuilder appendAnnotations(final StringBuilder builder,
+                       final List<AnnotationType> annotations) {
+               if ((builder != null) && (annotations != null)) {
+                       for (final AnnotationType annotation : annotations) {
+                               builder.append("@");
+                               builder.append(annotation.getPackageName());
+                               builder.append(".");
+                               builder.append(annotation.getName());
+
+                               if (annotation.containsParameters()) {
+                                       builder.append("(");
+                                       final List<AnnotationType.Parameter> parameters = annotation
+                                                       .getParameters();
+                                       appendAnnotationParams(builder, parameters);
+                                       builder.append(")");
+                               }
+                       }
+               }
+               return builder;
+       }
+
+       private static StringBuilder appendAnnotationParams(
+                       final StringBuilder builder,
+                       final List<AnnotationType.Parameter> parameters) {
+               if (parameters != null) {
+                       int i = 0;
+                       for (final AnnotationType.Parameter param : parameters) {
+                               if (param == null) {
+                                       continue;
+                               }
+                               if (i > 0) {
+                                       builder.append(", ");
+                               }
+                               final String paramName = param.getName();
+                               if (param.getValue() != null) {
+                                       builder.append(paramName);
+                                       builder.append(" = ");
+                                       builder.append(param.getValue());
+                               } else {
+                                       builder.append(paramName);
+                                       builder.append(" = {");
+                                       final List<String> values = param.getValues();
+                                       builder.append(values.get(0));
+                                       for (int j = 1; j < values.size(); ++j) {
+                                               builder.append(", ");
+                                               builder.append(values.get(j));
+                                       }
+                                       builder.append("}");
+                               }
+                               i++;
+                       }
+               }
+               return builder;
+       }
+
+       public static String createConstant(final Constant constant,
+                       final String indent,
+                       final Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       final String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+               builder.append(indent + PUBLIC + GAP + STATIC + GAP + FINAL + GAP);
+               builder.append(getExplicitType(constant.getType(), availableImports,
+                               currentPkg) + GAP + constant.getName());
+               builder.append(GAP + "=" + GAP);
+               builder.append(constant.getValue() + SC);
+               return builder.toString();
+       }
+
+       public static String createField(final GeneratedProperty property,
+                       final String indent,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       final String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+               builder.append(indent);
+               if (!property.getAnnotations().isEmpty()) {
+                       final List<AnnotationType> annotations = property.getAnnotations();
+                       appendAnnotations(builder, annotations);
+                       builder.append(NL);
+               }
+               builder.append(indent + PRIVATE + GAP);
+               builder.append(getExplicitType(property.getReturnType(),
+                               availableImports, currentPkg) + GAP + property.getName());
+               builder.append(SC);
+               return builder.toString();
+       }
+
+       /**
+        * Create method declaration in interface.
+        * 
+        * @param method
+        * @param indent
+        * @return
+        */
+       public static String createMethodDeclaration(final MethodSignature method,
+                       final String indent,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       final String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+
+               if (method == null) {
+                       throw new IllegalArgumentException(
+                                       "Method Signature parameter MUST be specified and cannot be NULL!");
+               }
+
+               final String comment = method.getComment();
+               final String name = method.getName();
+               if (name == null) {
+                       throw new IllegalStateException("Method Name cannot be NULL!");
+               }
+
+               final Type type = method.getReturnType();
+               if (type == null) {
+                       throw new IllegalStateException(
+                                       "Method Return type cannot be NULL!");
+               }
+
+               final List<Parameter> parameters = method.getParameters();
+
+               createComment(builder, comment, indent);
+               builder.append(NL);
+               builder.append(indent);
+
+               if (!method.getAnnotations().isEmpty()) {
+                       final List<AnnotationType> annotations = method.getAnnotations();
+                       appendAnnotations(builder, annotations);
+                       builder.append(NL);
+               }
+
+               builder.append(indent
+                               + getExplicitType(type, availableImports, currentPkg) + GAP
+                               + name);
+               builder.append(LB);
+               for (int i = 0; i < parameters.size(); i++) {
+                       Parameter p = parameters.get(i);
+                       String separator = COMMA;
+                       if (i + 1 == parameters.size()) {
+                               separator = "";
+                       }
+                       builder.append(getExplicitType(p.getType(), availableImports,
+                                       currentPkg) + GAP + p.getName() + separator);
+               }
+               builder.append(RB);
+               builder.append(SC);
+
+               return builder.toString();
+       }
+
+       public static String createConstructor(
+                       GeneratedTransferObject genTransferObject, final String indent,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports) {
+               final StringBuilder builder = new StringBuilder();
+
+               final String currentPkg = genTransferObject.getPackageName();
+               final List<GeneratedProperty> properties = genTransferObject
+                               .getProperties();
+               final List<GeneratedProperty> ctorParams = new ArrayList<GeneratedProperty>();
+               for (final GeneratedProperty property : properties) {
+                       if (property.isReadOnly()) {
+                               ctorParams.add(property);
+                       }
+               }
+
+               builder.append(indent);
+               builder.append(PUBLIC);
+               builder.append(GAP);
+               builder.append(genTransferObject.getName());
+               builder.append(LB);
+
+               if (!ctorParams.isEmpty()) {
+                       builder.append(getExplicitType(ctorParams.get(0).getReturnType(),
+                                       availableImports, currentPkg));
+                       builder.append(" ");
+                       builder.append(ctorParams.get(0).getName());
+                       for (int i = 1; i < ctorParams.size(); ++i) {
+                               final GeneratedProperty param = ctorParams.get(i);
+                               builder.append(", ");
+                               builder.append(getExplicitType(param.getReturnType(),
+                                               availableImports, currentPkg));
+                               builder.append(GAP);
+                               builder.append(param.getName());
+                       }
+               }
+               builder.append(RB + GAP + LCB + NL + indent + TAB + "super();" + NL);
+               if (!ctorParams.isEmpty()) {
+                       for (final GeneratedProperty property : ctorParams) {
+                               builder.append(indent);
+                               builder.append(TAB);
+                               builder.append("this.");
+                               builder.append(property.getName());
+                               builder.append(" = ");
+                               builder.append(property.getName());
+                               builder.append(SC);
+                               builder.append(NL);
+                       }
+               }
+               builder.append(indent);
+               builder.append(RCB);
+               return builder.toString();
+       }
+
+       public static String createGetter(final GeneratedProperty property,
+                       final String indent,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       final String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+
+               final Type type = property.getReturnType();
+               final String varName = property.getName();
+               final char first = Character.toUpperCase(varName.charAt(0));
+               final String methodName = "get" + first + varName.substring(1);
+
+               builder.append(indent + PUBLIC + GAP
+                               + getExplicitType(type, availableImports, currentPkg) + GAP
+                               + methodName);
+               builder.append(LB + RB + LCB + NL);
+
+               String currentIndent = indent + TAB;
+
+               builder.append(currentIndent + "return " + varName + SC + NL);
+
+               builder.append(indent + RCB);
+               return builder.toString();
+       }
+
+       public static String createSetter(final GeneratedProperty property,
+                       final String indent,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+
+               final Type type = property.getReturnType();
+               final String varName = property.getName();
+               final char first = Character.toUpperCase(varName.charAt(0));
+               final String methodName = "set" + first + varName.substring(1);
+
+               builder.append(indent + PUBLIC + GAP + "void" + GAP + methodName);
+               builder.append(LB + getExplicitType(type, availableImports, currentPkg)
+                               + GAP + varName + RB + LCB + NL);
+               String currentIndent = indent + TAB;
+               builder.append(currentIndent + "this." + varName + " = " + varName + SC
+                               + NL);
+               builder.append(indent + RCB);
+               return builder.toString();
+       }
+
+       public static String createHashCode(
+                       final List<GeneratedProperty> properties, final String indent) {
+               StringBuilder builder = new StringBuilder();
+               builder.append(indent + "public int hashCode() {" + NL);
+               builder.append(indent + TAB + "final int prime = 31;" + NL);
+               builder.append(indent + TAB + "int result = 1;" + NL);
+
+               for (GeneratedProperty property : properties) {
+                       String fieldName = property.getName();
+                       builder.append(indent + TAB + "result = prime * result + (("
+                                       + fieldName + " == null) ? 0 : " + fieldName
+                                       + ".hashCode());" + NL);
+               }
+
+               builder.append(indent + TAB + "return result;" + NL);
+               builder.append(indent + RCB + NL);
+               return builder.toString();
+       }
+
+       public static String createEquals(final GeneratedTransferObject type,
+                       final List<GeneratedProperty> properties, final String indent) {
+               StringBuilder builder = new StringBuilder();
+               final String indent1 = indent + TAB;
+               final String indent2 = indent1 + TAB;
+               final String indent3 = indent2 + TAB;
+
+               builder.append(indent + "public boolean equals(Object obj) {" + NL);
+               builder.append(indent1 + "if (this == obj) {" + NL);
+               builder.append(indent2 + "return true;" + NL);
+               builder.append(indent1 + "}" + NL);
+               builder.append(indent1 + "if (obj == null) {" + NL);
+               builder.append(indent2 + "return false;" + NL);
+               builder.append(indent1 + "}" + NL);
+               builder.append(indent1 + "if (getClass() != obj.getClass()) {" + NL);
+               builder.append(indent2 + "return false;" + NL);
+               builder.append(indent1 + "}" + NL);
+
+               String typeStr = type.getName();
+               builder.append(indent1 + typeStr + " other = (" + typeStr + ") obj;"
+                               + NL);
+
+               for (GeneratedProperty property : properties) {
+                       String fieldName = property.getName();
+                       builder.append(indent1 + "if (" + fieldName + " == null) {" + NL);
+                       builder.append(indent2 + "if (other." + fieldName + " != null) {"
+                                       + NL);
+                       builder.append(indent3 + "return false;" + NL);
+                       builder.append(indent2 + "}" + NL);
+                       builder.append(indent1 + "} else if (!" + fieldName
+                                       + ".equals(other." + fieldName + ")) {" + NL);
+                       builder.append(indent2 + "return false;" + NL);
+                       builder.append(indent1 + "}" + NL);
+               }
+
+               builder.append(indent1 + "return true;" + NL);
+
+               builder.append(indent + RCB + NL);
+               return builder.toString();
+       }
+
+       public static String createToString(final GeneratedTransferObject type,
+                       final List<GeneratedProperty> properties, final String indent) {
+               StringBuilder builder = new StringBuilder();
+               builder.append(indent);
+               builder.append("public String toString() {");
+               builder.append(NL);
+               builder.append(indent);
+               builder.append(TAB);
+               builder.append("StringBuilder builder = new StringBuilder();");
+               builder.append(NL);
+               builder.append(indent);
+               builder.append(TAB);
+               builder.append("builder.append(\"");
+               builder.append(type.getName());
+               builder.append(" [");
+
+               boolean first = true;
+               for (GeneratedProperty property : properties) {
+                       if (first) {
+                               builder.append(property.getName());
+                               builder.append("=\");");
+                               builder.append(NL);
+                               builder.append(indent);
+                               builder.append(TAB);
+                               builder.append("builder.append(");
+                               builder.append(property.getName());
+                               builder.append(");");
+                               first = false;
+                       } else {
+                               builder.append(NL);
+                               builder.append(indent);
+                               builder.append(TAB);
+                               builder.append("builder.append(\", ");
+                               builder.append(property.getName());
+                               builder.append("=\");");
+                               builder.append(NL);
+                               builder.append(indent);
+                               builder.append(TAB);
+                               builder.append("builder.append(");
+                               builder.append(property.getName());
+                               builder.append(");");
+                       }
+               }
+               builder.append(NL);
+               builder.append(indent);
+               builder.append(TAB);
+               builder.append("builder.append(\"]\");");
+               builder.append(NL);
+               builder.append(indent);
+               builder.append(TAB);
+               builder.append("return builder.toString();");
+
+               builder.append(NL);
+               builder.append(indent);
+               builder.append(RCB);
+               builder.append(NL);
+               return builder.toString();
+       }
+
+       public static String createEnum(final Enumeration enumeration,
+                       final String indent) {
+               if (enumeration == null || indent == null)
+                       throw new IllegalArgumentException();
+               final StringBuilder builder = new StringBuilder(indent + PUBLIC + GAP
+                               + ENUM + GAP + enumeration.getName() + GAP + LCB + NL);
+
+               String separator = COMMA + NL;
+               final List<Pair> values = enumeration.getValues();
+
+               for (int i = 0; i < values.size(); i++) {
+                       if (i + 1 == values.size()) {
+                               separator = SC;
+                       }
+                       builder.append(indent + TAB + values.get(i).getName() + LB
+                                       + values.get(i).getValue() + RB + separator);
+               }
+               builder.append(NL);
+               builder.append(NL);
+               final String ENUMERATION_NAME = "value";
+               final String ENUMERATION_TYPE = "int";
+               builder.append(indent + TAB + ENUMERATION_TYPE + GAP + ENUMERATION_NAME
+                               + SC);
+               builder.append(NL);
+               builder.append(indent + TAB + PRIVATE + GAP + enumeration.getName()
+                               + LB + ENUMERATION_TYPE + GAP + ENUMERATION_NAME + RB + GAP
+                               + LCB + NL);
+               builder.append(indent + TAB + TAB + "this." + ENUMERATION_NAME + GAP
+                               + "=" + GAP + ENUMERATION_NAME + SC + NL);
+               builder.append(indent + TAB + RCB + NL);
+
+               builder.append(indent + RCB);
+               builder.append(NL);
+               return builder.toString();
+       }
+
+       private static String getExplicitType(final Type type,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       final String currentPkg) {
+               if (type == null) {
+                       throw new IllegalArgumentException(
+                                       "Type parameter MUST be specified and cannot be NULL!");
+               }
+               String packageName = type.getPackageName();
+
+               LinkedHashMap<String, Integer> imports = availableImports.get(type
+                               .getName());
+
+               if ((imports != null && packageName
+                               .equals(findMaxValue(imports).get(0)))
+                               || packageName.equals(currentPkg)) {
+                       final StringBuilder builder = new StringBuilder(type.getName());
+                       if (type instanceof ParameterizedType) {
+                               ParameterizedType pType = (ParameterizedType) type;
+                               Type[] pTypes = pType.getActualTypeArguments();
+                               builder.append("<");
+                               builder.append(getParameters(pTypes, availableImports,
+                                               currentPkg));
+                               builder.append(">");
+                       }
+                       if (builder.toString().equals("Void")) {
+                               return "void";
+                       }
+                       return builder.toString();
+               } else {
+                       final StringBuilder builder = new StringBuilder();
+                       if (packageName.startsWith("java.lang")) {
+                               builder.append(type.getName());
+                       } else {
+                if (!packageName.isEmpty()) {
+                    builder.append(packageName + "." + type.getName());
                 } else {
-                    builder.append(paramName);
-                    builder.append(" = {");
-                    final List<String> values = param.getValues();
-                    builder.append(values.get(0));
-                    for (int j = 1; j < values.size(); ++j) {
-                        builder.append(", ");
-                        builder.append(values.get(j));
-                    }
-                    builder.append("}");
+                    builder.append(type.getName());
                 }
-                i++;
-            }
-        }
-        return builder;
-    }
-
-    public static String createConstant(final Constant constant,
-            final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports,
-            final String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-        builder.append(indent + PUBLIC + GAP + STATIC + GAP + FINAL + GAP);
-        builder.append(getExplicitType(constant.getType(), availableImports,
-                currentPkg) + GAP + constant.getName());
-        builder.append(GAP + "=" + GAP);
-        builder.append(constant.getValue() + SC);
-        return builder.toString();
-    }
-
-    public static String createField(final GeneratedProperty property,
-            final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            final String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-        builder.append(indent);
-        if (!property.getAnnotations().isEmpty()) {
-            final List<AnnotationType> annotations = property.getAnnotations();
-            appendAnnotations(builder, annotations);
-            builder.append(NL);
-        }
-        builder.append(indent + PRIVATE + GAP);
-        builder.append(getExplicitType(property.getReturnType(),
-                availableImports, currentPkg) + GAP + property.getName());
-        builder.append(SC);
-        return builder.toString();
-    }
-
-    /**
-     * Create method declaration in interface.
-     *
-     * @param method
-     * @param indent
-     * @return
-     */
-    public static String createMethodDeclaration(final MethodSignature method,
-            final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            final String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-
-        if (method == null) {
-            throw new IllegalArgumentException(
-                    "Method Signature parameter MUST be specified and cannot be NULL!");
-        }
-
-        final String comment = method.getComment();
-        final String name = method.getName();
-        if (name == null) {
-            throw new IllegalStateException("Method Name cannot be NULL!");
-        }
-
-        final Type type = method.getReturnType();
-        if (type == null) {
-            throw new IllegalStateException(
-                    "Method Return type cannot be NULL!");
-        }
-
-        final List<Parameter> parameters = method.getParameters();
-
-        createComment(builder, comment, indent);
-        builder.append(NL);
-        builder.append(indent);
-
-        if (!method.getAnnotations().isEmpty()) {
-            final List<AnnotationType> annotations = method.getAnnotations();
-            appendAnnotations(builder, annotations);
-            builder.append(NL);
-        }
-
-        builder.append(indent
-                + getExplicitType(type, availableImports, currentPkg) + GAP
-                + name);
-        builder.append(LB);
-        for (int i = 0; i < parameters.size(); i++) {
-            Parameter p = parameters.get(i);
-            String separator = COMMA;
-            if (i + 1 == parameters.size()) {
-                separator = "";
-            }
-            builder.append(getExplicitType(p.getType(), availableImports,
-                    currentPkg) + GAP + p.getName() + separator);
-        }
-        builder.append(RB);
-        builder.append(SC);
-
-        return builder.toString();
-    }
-
-    public static String createConstructor(
-            GeneratedTransferObject genTransferObject, final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports) {
-        final StringBuilder builder = new StringBuilder();
-
-        final String currentPkg = genTransferObject.getPackageName();
-        final List<GeneratedProperty> properties = genTransferObject
-                .getProperties();
-        final List<GeneratedProperty> ctorParams = new ArrayList<GeneratedProperty>();
-        for (final GeneratedProperty property : properties) {
-            if (property.isReadOnly()) {
-                ctorParams.add(property);
-            }
-        }
-
-        builder.append(indent);
-        builder.append(PUBLIC);
-        builder.append(GAP);
-        builder.append(genTransferObject.getName());
-        builder.append(LB);
-
-        if (!ctorParams.isEmpty()) {
-            builder.append(getExplicitType(ctorParams.get(0).getReturnType(),
-                    availableImports, currentPkg));
-            builder.append(" ");
-            builder.append(ctorParams.get(0).getName());
-            for (int i = 1; i < ctorParams.size(); ++i) {
-                final GeneratedProperty param = ctorParams.get(i);
-                builder.append(", ");
-                builder.append(getExplicitType(param.getReturnType(),
-                        availableImports, currentPkg));
-                builder.append(GAP);
-                builder.append(param.getName());
-            }
-        }
-        builder.append(RB + GAP + LCB + NL + indent + TAB + "super();" + NL);
-        if (!ctorParams.isEmpty()) {
-            for (final GeneratedProperty property : ctorParams) {
-                builder.append(indent);
-                builder.append(TAB);
-                builder.append("this.");
-                builder.append(property.getName());
-                builder.append(" = ");
-                builder.append(property.getName());
-                builder.append(SC);
-                builder.append(NL);
-            }
-        }
-        builder.append(indent);
-        builder.append(RCB);
-        return builder.toString();
-    }
-
-    public static String createGetter(final GeneratedProperty property,
-            final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            final String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-
-        final Type type = property.getReturnType();
-        final String varName = property.getName();
-        final char first = Character.toUpperCase(varName.charAt(0));
-        final String methodName = "get" + first + varName.substring(1);
-
-        builder.append(indent + PUBLIC + GAP
-                + getExplicitType(type, availableImports, currentPkg) + GAP
-                + methodName);
-        builder.append(LB + RB + LCB + NL);
-
-        String currentIndent = indent + TAB;
-
-        builder.append(currentIndent + "return " + varName + SC + NL);
-
-        builder.append(indent + RCB);
-        return builder.toString();
-    }
-
-    public static String createSetter(final GeneratedProperty property,
-            final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-
-        final Type type = property.getReturnType();
-        final String varName = property.getName();
-        final char first = Character.toUpperCase(varName.charAt(0));
-        final String methodName = "set" + first + varName.substring(1);
-
-        builder.append(indent + PUBLIC + GAP + "void" + GAP + methodName);
-        builder.append(LB + getExplicitType(type, availableImports, currentPkg)
-                + GAP + varName + RB + LCB + NL);
-        String currentIndent = indent + TAB;
-        builder.append(currentIndent + "this." + varName + " = " + varName + SC
-                + NL);
-        builder.append(indent + RCB);
-        return builder.toString();
-    }
-
-    public static String createHashCode(
-            final List<GeneratedProperty> properties, final String indent) {
-        StringBuilder builder = new StringBuilder();
-        builder.append(indent + "public int hashCode() {" + NL);
-        builder.append(indent + TAB + "final int prime = 31;" + NL);
-        builder.append(indent + TAB + "int result = 1;" + NL);
-
-        for (GeneratedProperty property : properties) {
-            String fieldName = property.getName();
-            builder.append(indent + TAB + "result = prime * result + (("
-                    + fieldName + " == null) ? 0 : " + fieldName
-                    + ".hashCode());" + NL);
-        }
-
-        builder.append(indent + TAB + "return result;" + NL);
-        builder.append(indent + RCB + NL);
-        return builder.toString();
-    }
-
-    public static String createEquals(final GeneratedTransferObject type,
-            final List<GeneratedProperty> properties, final String indent) {
-        StringBuilder builder = new StringBuilder();
-        final String indent1 = indent + TAB;
-        final String indent2 = indent1 + TAB;
-        final String indent3 = indent2 + TAB;
-
-        builder.append(indent + "public boolean equals(Object obj) {" + NL);
-        builder.append(indent1 + "if (this == obj) {" + NL);
-        builder.append(indent2 + "return true;" + NL);
-        builder.append(indent1 + "}" + NL);
-        builder.append(indent1 + "if (obj == null) {" + NL);
-        builder.append(indent2 + "return false;" + NL);
-        builder.append(indent1 + "}" + NL);
-        builder.append(indent1 + "if (getClass() != obj.getClass()) {" + NL);
-        builder.append(indent2 + "return false;" + NL);
-        builder.append(indent1 + "}" + NL);
-
-        String typeStr = type.getName();
-        builder.append(indent1 + typeStr + " other = (" + typeStr + ") obj;"
-                + NL);
-
-        for (GeneratedProperty property : properties) {
-            String fieldName = property.getName();
-            builder.append(indent1 + "if (" + fieldName + " == null) {" + NL);
-            builder.append(indent2 + "if (other." + fieldName + " != null) {"
-                    + NL);
-            builder.append(indent3 + "return false;" + NL);
-            builder.append(indent2 + "}" + NL);
-            builder.append(indent1 + "} else if (!" + fieldName
-                    + ".equals(other." + fieldName + ")) {" + NL);
-            builder.append(indent2 + "return false;" + NL);
-            builder.append(indent1 + "}" + NL);
-        }
-
-        builder.append(indent1 + "return true;" + NL);
-
-        builder.append(indent + RCB + NL);
-        return builder.toString();
-    }
-
-    public static String createToString(final GeneratedTransferObject type,
-            final List<GeneratedProperty> properties, final String indent) {
-        StringBuilder builder = new StringBuilder();
-        builder.append(indent);
-        builder.append("public String toString() {");
-        builder.append(NL);
-        builder.append(indent);
-        builder.append(TAB);
-        builder.append("StringBuilder builder = new StringBuilder();");
-        builder.append(NL);
-        builder.append(indent);
-        builder.append(TAB);
-        builder.append("builder.append(\"");
-        builder.append(type.getName());
-        builder.append(" [");
-
-        boolean first = true;
-        for (GeneratedProperty property : properties) {
-            if (first) {
-                builder.append(property.getName());
-                builder.append("=\");");
-                builder.append(NL);
-                builder.append(indent);
-                builder.append(TAB);
-                builder.append("builder.append(");
-                builder.append(property.getName());
-                builder.append(");");
-                first = false;
-            } else {
-                builder.append(NL);
-                builder.append(indent);
-                builder.append(TAB);
-                builder.append("builder.append(\", ");
-                builder.append(property.getName());
-                builder.append("=\");");
-                builder.append(NL);
-                builder.append(indent);
-                builder.append(TAB);
-                builder.append("builder.append(\", ");
-                builder.append(property.getName());
-                builder.append(");");
-            }
-        }
-        builder.append(NL);
-        builder.append(indent);
-        builder.append(TAB);
-        builder.append("builder.append(\"]\");");
-        builder.append(NL);
-        builder.append(indent);
-        builder.append(TAB);
-        builder.append("return builder.toString();");
-
-        builder.append(NL);
-        builder.append(indent);
-        builder.append(RCB);
-        builder.append(NL);
-        return builder.toString();
-    }
-
-    public static String createEnum(final Enumeration enumeration,
-            final String indent) {
-        final StringBuilder builder = new StringBuilder(indent + ENUM + GAP
-                + enumeration.getName() + GAP + LCB + NL);
-
-        String separator = COMMA;
-        final List<Pair> values = enumeration.getValues();
-        builder.append(indent + TAB);
-        for (int i = 0; i < values.size(); i++) {
-            if (i + 1 == values.size()) {
-                separator = SC;
-            }
-            builder.append(values.get(i).getName() + separator);
-        }
-        builder.append(NL);
-        builder.append(indent + RCB);
-        return builder.toString();
-    }
-
-    private static String getExplicitType(final Type type,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            final String currentPkg) {
-        if (type == null) {
-            throw new IllegalArgumentException(
-                    "Type parameter MUST be specified and cannot be NULL!");
-        }
-        String packageName = type.getPackageName();
-
-        LinkedHashMap<String, Integer> imports = availableImports.get(type
-                .getName());
-
-        if ((imports != null && packageName
-                .equals(findMaxValue(imports).get(0)))
-                || packageName.equals(currentPkg)) {
-            final StringBuilder builder = new StringBuilder(type.getName());
-            if (type instanceof ParameterizedType) {
-                ParameterizedType pType = (ParameterizedType) type;
-                Type[] pTypes = pType.getActualTypeArguments();
-                builder.append("<");
-                builder.append(getParameters(pTypes, availableImports,
-                        currentPkg));
-                builder.append(">");
-            }
-            if (builder.toString().equals("Void")) {
-                return "void";
-            }
-            return builder.toString();
-        } else {
-            final StringBuilder builder = new StringBuilder();
-            if (packageName.startsWith("java.lang")) {
-                builder.append(type.getName());
-            } else {
-                builder.append(packageName + "." + type.getName());
-            }
-            if (type instanceof ParameterizedType) {
-                ParameterizedType pType = (ParameterizedType) type;
-                Type[] pTypes = pType.getActualTypeArguments();
-                builder.append("<");
-                builder.append(getParameters(pTypes, availableImports,
-                        currentPkg));
-                builder.append(">");
-            }
-            if (builder.toString().equals("Void")) {
-                return "void";
-            }
-            return builder.toString();
-        }
-    }
-
-    private static String getParameters(final Type[] pTypes,
-            Map<String, LinkedHashMap<String, Integer>> availableImports,
-            String currentPkg) {
-        final StringBuilder builder = new StringBuilder();
-        for (int i = 0; i < pTypes.length; i++) {
-            Type t = pTypes[i];
-
-            String separator = COMMA;
-            if (i + 1 == pTypes.length) {
-                separator = "";
-            }
-            builder.append(getExplicitType(t, availableImports, currentPkg)
-                    + separator);
-        }
-        return builder.toString();
-    }
-
-    private static List<String> findMaxValue(
-            LinkedHashMap<String, Integer> imports) {
-        final List<String> result = new ArrayList<String>();
-
-        int maxValue = 0;
-        int currentValue = 0;
-        for (Map.Entry<String, Integer> entry : imports.entrySet()) {
-            currentValue = entry.getValue();
-            if (currentValue > maxValue) {
-                result.clear();
-                result.add(entry.getKey());
-            } else if (currentValue == maxValue) {
-                result.add(entry.getKey());
-            }
-        }
-        return result;
-    }
-
-    private static void createComment(final StringBuilder builder,
-            final String comment, final String indent) {
-        if (comment != null && comment.length() > 0) {
-            builder.append(indent + "/*" + NL);
-            builder.append(indent + comment + NL);
-            builder.append(indent + "*/" + NL);
-        }
-    }
-
-    public static Map<String, LinkedHashMap<String, Integer>> createImports(
-            GeneratedType genType) {
-        final Map<String, LinkedHashMap<String, Integer>> imports = new HashMap<String, LinkedHashMap<String, Integer>>();
-        final String genTypePkg = genType.getPackageName();
-
-        final List<Constant> constants = genType.getConstantDefinitions();
-        final List<MethodSignature> methods = genType.getMethodDefinitions();
-        List<Type> impl = genType.getImplements();
-
-        // IMPLEMENTATIONS
-        if (impl != null) {
-            for (Type t : impl) {
-                addTypeToImports(t, imports, genTypePkg);
-            }
-        }
-
-        // CONSTANTS
-        if (constants != null) {
-            for (Constant c : constants) {
-                Type ct = c.getType();
-                addTypeToImports(ct, imports, genTypePkg);
-            }
-        }
-
-        // METHODS
-        if (methods != null) {
-            for (MethodSignature m : methods) {
-                Type ct = m.getReturnType();
-                addTypeToImports(ct, imports, genTypePkg);
-                for (MethodSignature.Parameter p : m.getParameters()) {
-                    addTypeToImports(p.getType(), imports, genTypePkg);
-                }
-            }
-        }
-
-        // PROPERTIES
-        if (genType instanceof GeneratedTransferObject) {
-            GeneratedTransferObject genTO = (GeneratedTransferObject) genType;
-
-            List<GeneratedProperty> props = genTO.getProperties();
-            if (props != null) {
-                for (GeneratedProperty prop : props) {
-                    Type pt = prop.getReturnType();
-                    addTypeToImports(pt, imports, genTypePkg);
-                }
-            }
-        }
-
-        return imports;
-    }
-
-    private static void addTypeToImports(Type type,
-            Map<String, LinkedHashMap<String, Integer>> importedTypes,
-            String genTypePkg) {
-        String typeName = type.getName();
-        String typePkg = type.getPackageName();
-        if (typePkg.startsWith("java.lang") || typePkg.equals(genTypePkg)) {
-            return;
-        }
-        LinkedHashMap<String, Integer> packages = importedTypes.get(typeName);
-        if (packages == null) {
-            packages = new LinkedHashMap<String, Integer>();
-            packages.put(typePkg, 1);
-            importedTypes.put(typeName, packages);
-        } else {
-            Integer occurrence = packages.get(typePkg);
-            if (occurrence == null) {
-                packages.put(typePkg, 1);
-            } else {
-                occurrence++;
-                packages.put(typePkg, occurrence);
-            }
-        }
-
-        if (type instanceof ParameterizedType) {
-            ParameterizedType pt = (ParameterizedType) type;
-            Type[] params = pt.getActualTypeArguments();
-            for (Type param : params) {
-                addTypeToImports(param, importedTypes, genTypePkg);
-            }
-        }
-    }
-
-    public static List<String> createImportLines(
-            Map<String, LinkedHashMap<String, Integer>> imports) {
-        List<String> importLines = new ArrayList<String>();
-
-        for (Map.Entry<String, LinkedHashMap<String, Integer>> entry : imports
-                .entrySet()) {
-            String typeName = entry.getKey();
-            LinkedHashMap<String, Integer> typePkgMap = entry.getValue();
-            String typePkg = typePkgMap.keySet().iterator().next();
-            importLines.add("import " + typePkg + "." + typeName + SC);
-        }
-        return importLines;
-    }
+
+                       }
+                       if (type instanceof ParameterizedType) {
+                               ParameterizedType pType = (ParameterizedType) type;
+                               Type[] pTypes = pType.getActualTypeArguments();
+                               builder.append("<");
+                               builder.append(getParameters(pTypes, availableImports,
+                                               currentPkg));
+                               builder.append(">");
+                       }
+                       if (builder.toString().equals("Void")) {
+                               return "void";
+                       }
+                       return builder.toString();
+               }
+       }
+
+       private static String getParameters(final Type[] pTypes,
+                       Map<String, LinkedHashMap<String, Integer>> availableImports,
+                       String currentPkg) {
+               final StringBuilder builder = new StringBuilder();
+               for (int i = 0; i < pTypes.length; i++) {
+                       Type t = pTypes[i];
+
+                       String separator = COMMA;
+                       if (i + 1 == pTypes.length) {
+                               separator = "";
+                       }
+                       builder.append(getExplicitType(t, availableImports, currentPkg)
+                                       + separator);
+               }
+               return builder.toString();
+       }
+
+       private static List<String> findMaxValue(
+                       LinkedHashMap<String, Integer> imports) {
+               final List<String> result = new ArrayList<String>();
+
+               int maxValue = 0;
+               int currentValue = 0;
+               for (Map.Entry<String, Integer> entry : imports.entrySet()) {
+                       currentValue = entry.getValue();
+                       if (currentValue > maxValue) {
+                               result.clear();
+                               result.add(entry.getKey());
+                       } else if (currentValue == maxValue) {
+                               result.add(entry.getKey());
+                       }
+               }
+               return result;
+       }
+
+       private static void createComment(final StringBuilder builder,
+                       final String comment, final String indent) {
+               if (comment != null && comment.length() > 0) {
+                       builder.append(indent + "/*" + NL);
+                       builder.append(indent + comment + NL);
+                       builder.append(indent + "*/" + NL);
+               }
+       }
+
+       public static Map<String, LinkedHashMap<String, Integer>> createImports(
+                       GeneratedType genType) {
+               final Map<String, LinkedHashMap<String, Integer>> imports = new HashMap<String, LinkedHashMap<String, Integer>>();
+               final String genTypePkg = genType.getPackageName();
+
+               final List<Constant> constants = genType.getConstantDefinitions();
+               final List<MethodSignature> methods = genType.getMethodDefinitions();
+               List<Type> impl = genType.getImplements();
+
+               // IMPLEMENTATIONS
+               if (impl != null) {
+                       for (Type t : impl) {
+                               addTypeToImports(t, imports, genTypePkg);
+                       }
+               }
+
+               // CONSTANTS
+               if (constants != null) {
+                       for (Constant c : constants) {
+                               Type ct = c.getType();
+                               addTypeToImports(ct, imports, genTypePkg);
+                       }
+               }
+
+               // METHODS
+               if (methods != null) {
+                       for (MethodSignature m : methods) {
+                               Type ct = m.getReturnType();
+                               addTypeToImports(ct, imports, genTypePkg);
+                               for (MethodSignature.Parameter p : m.getParameters()) {
+                                       addTypeToImports(p.getType(), imports, genTypePkg);
+                               }
+                       }
+               }
+
+               // PROPERTIES
+               if (genType instanceof GeneratedTransferObject) {
+                       GeneratedTransferObject genTO = (GeneratedTransferObject) genType;
+
+                       List<GeneratedProperty> props = genTO.getProperties();
+                       if (props != null) {
+                               for (GeneratedProperty prop : props) {
+                                       Type pt = prop.getReturnType();
+                                       addTypeToImports(pt, imports, genTypePkg);
+                               }
+                       }
+               }
+
+               return imports;
+       }
+
+       private static void addTypeToImports(Type type,
+                       Map<String, LinkedHashMap<String, Integer>> importedTypes,
+                       String genTypePkg) {
+               String typeName = type.getName();
+               String typePkg = type.getPackageName();
+               if (typePkg.startsWith("java.lang") || typePkg.equals(genTypePkg) ||
+                typePkg.isEmpty()) {
+                       return;
+               }
+               LinkedHashMap<String, Integer> packages = importedTypes.get(typeName);
+               if (packages == null) {
+                       packages = new LinkedHashMap<String, Integer>();
+                       packages.put(typePkg, 1);
+                       importedTypes.put(typeName, packages);
+               } else {
+                       Integer occurrence = packages.get(typePkg);
+                       if (occurrence == null) {
+                               packages.put(typePkg, 1);
+                       } else {
+                               occurrence++;
+                               packages.put(typePkg, occurrence);
+                       }
+               }
+
+               if (type instanceof ParameterizedType) {
+                       ParameterizedType pt = (ParameterizedType) type;
+                       Type[] params = pt.getActualTypeArguments();
+                       for (Type param : params) {
+                               addTypeToImports(param, importedTypes, genTypePkg);
+                       }
+               }
+       }
+
+       public static List<String> createImportLines(
+                       Map<String, LinkedHashMap<String, Integer>> imports) {
+               List<String> importLines = new ArrayList<String>();
+
+               for (Map.Entry<String, LinkedHashMap<String, Integer>> entry : imports
+                               .entrySet()) {
+                       String typeName = entry.getKey();
+                       LinkedHashMap<String, Integer> typePkgMap = entry.getValue();
+                       String typePkg = typePkgMap.keySet().iterator().next();
+                       importLines.add("import " + typePkg + "." + typeName + SC);
+               }
+               return importLines;
+       }
 
 }
index abaf4fad21bb03caa81b2b1d82677bfbd7718618..38d3bcdc070dd4522a7c9d28ef28e2721bd10561 100644 (file)
@@ -24,63 +24,86 @@ import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public class InterfaceGenerator implements CodeGenerator {
-
-    private Map<String, LinkedHashMap<String, Integer>> imports;
-
-    public Writer generate(Type type) throws IOException {
-        Writer writer = new StringWriter();
-        if (type instanceof GeneratedType
-                && !(type instanceof GeneratedTransferObject)) {
-            GeneratedType genType = (GeneratedType) type;
-            imports = GeneratorUtil.createImports(genType);
-
-            final String currentPkg = genType.getPackageName();
-            final List<Constant> constants = genType.getConstantDefinitions();
-            final List<MethodSignature> methods = genType
-                    .getMethodDefinitions();
-            final List<Enumeration> enums = genType.getEnumDefintions();
-
-            writer.write(GeneratorUtil.createPackageDeclaration(genType
-                    .getPackageName()));
-            writer.write(NL);
-
-            List<String> importLines = GeneratorUtil.createImportLines(imports);
-            for (String line : importLines) {
-                writer.write(line + NL);
-            }
-            writer.write(NL);
-
-            writer.write(GeneratorUtil.createIfcDeclaration(genType, "",
-                    imports));
-            writer.write(NL);
-
-            if (constants != null) {
-                for (Constant c : constants) {
-                    writer.write(GeneratorUtil.createConstant(c, TAB, imports,
-                            currentPkg) + NL);
-                }
-                writer.write(NL);
-            }
-
-            if (methods != null) {
-                for (MethodSignature m : methods) {
-                    writer.write(GeneratorUtil.createMethodDeclaration(m, TAB,
-                            imports, currentPkg) + NL);
-                }
-                writer.write(NL);
-            }
-
-            if (enums != null) {
-                for (Enumeration e : enums) {
-                    writer.write(GeneratorUtil.createEnum(e, TAB) + NL);
-                }
-                writer.write(NL);
-            }
-
-            writer.write(RCB);
-        }
-        return writer;
-    }
+public final class InterfaceGenerator implements CodeGenerator {
+
+       private Map<String, LinkedHashMap<String, Integer>> imports;
+
+       private String generateEnums(List<Enumeration> enums) {
+               String result = "";
+               if (enums != null) {
+                       EnumGenerator enumGenerator = new EnumGenerator();
+                       for (Enumeration en : enums) {
+                               try {
+                                       result = result
+                                                       + (enumGenerator.generateInnerEnumeration(en, TAB).toString() + NL);
+                               } catch (IOException e) {
+                                       e.printStackTrace();
+                               }
+                       }
+               }
+               return result;
+       }
+
+       private String generateConstants(List<Constant> constants, String pkgName) {
+               String result = "";
+               if (constants != null) {
+                       for (Constant c : constants) {
+                               result = result
+                                               + GeneratorUtil
+                                                               .createConstant(c, TAB, imports, pkgName) + NL;
+                       }
+                       result.concat(NL);
+               }
+               return result;
+       }
+
+       public String generateMethods(List<MethodSignature> methods, String pkgName) {
+               String result = "";
+
+               if (methods != null) {
+                       for (MethodSignature m : methods) {
+                               result = result
+                                               + GeneratorUtil.createMethodDeclaration(m, TAB,
+                                                               imports, pkgName) + NL;
+                       }
+                       result = result + NL;
+               }
+               return result;
+       }
+
+       public Writer generate(Type type) throws IOException {
+               Writer writer = new StringWriter();
+               if (type instanceof GeneratedType
+                               && !(type instanceof GeneratedTransferObject)) {
+                       GeneratedType genType = (GeneratedType) type;
+                       imports = GeneratorUtil.createImports(genType);
+
+                       final String currentPkg = genType.getPackageName();
+                       final List<Constant> constants = genType.getConstantDefinitions();
+                       final List<MethodSignature> methods = genType
+                                       .getMethodDefinitions();
+                       final List<Enumeration> enums = genType.getEnumDefintions();
+
+                       writer.write(GeneratorUtil.createPackageDeclaration(genType
+                                       .getPackageName()));
+                       writer.write(NL);
+
+                       List<String> importLines = GeneratorUtil.createImportLines(imports);
+                       for (String line : importLines) {
+                               writer.write(line + NL);
+                       }
+                       writer.write(NL);
+                       writer.write(GeneratorUtil.createIfcDeclaration(genType, "",
+                                       imports));
+                       writer.write(NL);
+
+                       writer.write(generateEnums(enums));
+                       writer.write(generateConstants(constants, currentPkg));
+                       writer.write(generateMethods(methods, currentPkg));
+
+                       writer.write(RCB);
+               }
+               return writer;
+       }
 
 }
index 3295becba6bbb27a78f1cbc5dd7ed7e8c3f4926e..cfcd6a4afc6d25f5a84cf216ae4e4f3b7cc3735d 100644 (file)
@@ -134,4 +134,28 @@ public class ClassCodeGeneratorTest {
             e.printStackTrace();
         }
     }
+
+    @Test
+    public void toStringTest() {
+        final GeneratedTOBuilder toBuilder = new GeneratedTOBuilderImpl(
+                "simple.pack", "DefCtor");
+
+        GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
+        propBuilder.addReturnType(Types.typeForClass(String.class));
+        propBuilder.setReadOnly(false);
+        toBuilder.addToStringProperty(propBuilder);
+
+        propBuilder = toBuilder.addProperty("bar");
+        propBuilder.addReturnType(Types.typeForClass(Integer.class));
+        propBuilder.setReadOnly(false);
+        toBuilder.addToStringProperty(propBuilder);
+        final GeneratedTransferObject genTO = toBuilder.toInstance();
+        final ClassCodeGenerator clsGen = new ClassCodeGenerator();
+        try {
+            final Writer writer = clsGen.generate(genTO);
+            assertNotNull(writer);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
 }
index bf539eb8fe43eb3149352501a10df2cec95cb385..db42d32fe6e7415f0ee90084c869fb06db9856c1 100644 (file)
@@ -29,6 +29,7 @@ import org.junit.Test;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.impl.BindingGeneratorImpl;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
@@ -117,6 +118,7 @@ public class GeneratorJavaFileTest {
         final List<Type> types = bindingGenerator.generateTypes(context);
         final Set<GeneratedType> typesToGenerate = new HashSet<GeneratedType>();
         final Set<GeneratedTransferObject> tosToGenerate = new HashSet<GeneratedTransferObject>();
+        final Set<Enumeration> enumerationToGenerate = new HashSet<Enumeration>();
         for (Type type : types) {
             if (type instanceof GeneratedType
                     && !(type instanceof GeneratedTransferObject)) {
@@ -126,10 +128,13 @@ public class GeneratorJavaFileTest {
             if (type instanceof GeneratedTransferObject) {
                 tosToGenerate.add((GeneratedTransferObject) type);
             }
+            if (type instanceof Enumeration) {
+               enumerationToGenerate.add((Enumeration) type);                  
+            }
         }
 
         final GeneratorJavaFile generator = new GeneratorJavaFile(
-                typesToGenerate, tosToGenerate);
+                typesToGenerate, tosToGenerate, enumerationToGenerate);
         generator.generateToFile(new File(GENERATOR_OUTPUT_PATH));
 
         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
index 491cef6bcc3caf99bfb61e83f10d1aa678cc7332..f6b80bc66640e9b5f4a9ea9ff76e98bae77a81f5 100644 (file)
@@ -20,6 +20,7 @@ import org.apache.maven.project.MavenProject;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.impl.BindingGeneratorImpl;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.opendaylight.controller.sal.java.api.generator.GeneratorJavaFile;
@@ -27,27 +28,30 @@ import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang2sources.spi.CodeGenerator;
 
-public class CodeGeneratorImpl implements CodeGenerator {
+public final class CodeGeneratorImpl implements CodeGenerator {
 
-    @Override
-    public Collection<File> generateSources(SchemaContext context,
+       @Override
+       public Collection<File> generateSources(SchemaContext context,
             File outputBaseDir, Set<Module> yangModules) throws IOException {
 
-        final BindingGenerator bindingGenerator = new BindingGeneratorImpl();
-        final List<Type> types = bindingGenerator.generateTypes(context);
-        final Set<GeneratedType> typesToGenerate = new HashSet<GeneratedType>();
-        final Set<GeneratedTransferObject> tosToGenerate = new HashSet<GeneratedTransferObject>();
-        for (Type type : types) {
-            if (type instanceof GeneratedTransferObject) {
-                tosToGenerate.add((GeneratedTransferObject) type);
-            } else if (type instanceof GeneratedType) {
-                typesToGenerate.add((GeneratedType) type);
-            }
+               final BindingGenerator bindingGenerator = new BindingGeneratorImpl();
+               final List<Type> types = bindingGenerator.generateTypes(context);
+               final Set<GeneratedType> typesToGenerate = new HashSet<>();
+               final Set<GeneratedTransferObject> tosToGenerate = new HashSet<>();
+               final Set<Enumeration> enumsToGenerate = new HashSet<>();
 
+               for (Type type : types) {
+                       if (type instanceof GeneratedTransferObject) {
+                               tosToGenerate.add((GeneratedTransferObject) type);
+                       } else if (type instanceof GeneratedType) {
+                               typesToGenerate.add((GeneratedType) type);
+                       } else if (type instanceof Enumeration) {
+                               enumsToGenerate.add((Enumeration) type);
+                       }
         }
 
         final GeneratorJavaFile generator = new GeneratorJavaFile(
-                typesToGenerate, tosToGenerate);
+                               typesToGenerate, tosToGenerate, enumsToGenerate);
 
         return generator.generateToFile(outputBaseDir);
     }
@@ -71,6 +75,6 @@ public class CodeGeneratorImpl implements CodeGenerator {
     @Override
     public void setMavenProject(MavenProject project) {
         // no additional information needed
-    }
+       }
 
 }
index 280284bcba38d9378a54c225d53a69f7ad02dc5a..9532d4efc9f92a4fbabe32e6ab11b79665e81e37 100644 (file)
@@ -11,6 +11,7 @@ import static org.junit.Assert.*;
 import static org.junit.matchers.JUnitMatchers.*;
 
 import java.io.File;
+import java.net.URL;
 
 import org.apache.maven.it.VerificationException;
 import org.apache.maven.it.Verifier;
@@ -47,8 +48,12 @@ public class YangToSourcesPluginTestIT {
         Verifier v = setUp("AdditionalConfig/", false);
         v.verifyTextInLog("[DEBUG] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {nm1=abcd=a.b.c.d, nm2=abcd2=a.b.c.d.2}");
         v.verifyTextInLog("[DEBUG] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {c1=config}");
-        v.verifyTextInLog("../files marked as resources: META-INF/yang");
-        v.verifyTextInLog("target/generated-resources marked as resources for generator: org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl");
+        v.verifyTextInLog(File.separator
+                + "files marked as resources: META-INF" + File.separator
+                + "yang");
+        v.verifyTextInLog("target"
+                + File.separator
+                + "generated-resources marked as resources for generator: org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl");
     }
 
     @Test
@@ -104,8 +109,10 @@ public class YangToSourcesPluginTestIT {
 
     static Verifier setUp(String project, boolean ignoreF)
             throws VerificationException {
-        Verifier verifier = new Verifier(new File("src/test/resources/"
-                + project).getAbsolutePath());
+        final URL path = YangToSourcesPluginTestIT.class.getResource("/"
+                + project + "pom.xml");
+        File parent = new File(path.getPath());
+        Verifier verifier = new Verifier(parent.getParent());
         if (ignoreF)
             verifier.addCliOption("-fn");
         verifier.setMavenDebug(true);
@@ -121,8 +128,8 @@ public class YangToSourcesPluginTestIT {
 
     @Test
     public void testFindResourceOnCp() throws VerificationException {
-        Verifier v1 = new Verifier(
-                new File("src/test/resources/GenerateTest1/").getAbsolutePath());
+        Verifier v1 = new Verifier(new File(getClass().getResource(
+                "/GenerateTest1/pom.xml").getPath()).getParent());
         v1.executeGoal("clean");
         v1.executeGoal("package");
         v1.assertFilePresent("target/classes/META-INF/yang/testfile1.yang");
@@ -137,5 +144,4 @@ public class YangToSourcesPluginTestIT {
         v2.assertFileNotPresent("target/classes/META-INF/yang/testfile2.yang");
         v2.assertFileNotPresent("target/classes/META-INF/yang/testfile3.yang");
     }
-
 }
index b608637e6be8bb13f2c32331226b732e4981a187..ed1fbf7c56ab895e5cc2e20435c282295ac5e86f 100644 (file)
                                     </outputBaseDir>
                                 </generator>
                             </codeGenerators>
-                            <resourceProviders>
-                                <provider>
-                                    <resourceProviderClass>
-                                        org.opendaylight.controller.yang2sources.spi.ResourceProviderTestImpl
-                                    </resourceProviderClass>
-                                    <outputBaseDir>
-                                        outDir/
-                                    </outputBaseDir>
-                                </provider>
-                            </resourceProviders>
                         </configuration>
                     </execution>
                 </executions>
index 7b83af42428d9e6ebbda79b301e80f1672c114fd..e3b0b31215bef2a6deac7457d152d19ec81d1115 100644 (file)
@@ -216,7 +216,7 @@ final class Util {
                         String entryName = entry.getName();
 
                         if (entryName
-                                .startsWith(YangToSourcesProcessor.META_INF_YANG_STRING)) {
+                                .startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)) {
                             if (entry.isDirectory() == false
                                     && entryName.endsWith(".yang")) {
                                 foundFilesForReporting.add(entryName);
index 770eeee964895bd0714cdc00eb0e08d7850923cf..a7b7f429ccbffbd9bf4f4593094989446914105f 100644 (file)
@@ -40,6 +40,7 @@ class YangToSourcesProcessor {
     static final String LOG_PREFIX = "yang-to-sources:";
     static final String META_INF_YANG_STRING = "META-INF" + File.separator
             + "yang";
+    static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
     static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
 
     private final Log log;
@@ -51,8 +52,8 @@ class YangToSourcesProcessor {
 
     @VisibleForTesting
     YangToSourcesProcessor(Log log, File yangFilesRootDir,
-            List<CodeGeneratorArg> codeGenerators, MavenProject project,
-            boolean inspectDependencies, YangProvider yangProvider) {
+                           List<CodeGeneratorArg> codeGenerators, MavenProject project,
+                           boolean inspectDependencies, YangProvider yangProvider) {
         this.log = Util.checkNotNull(log, "log");
         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir,
                 "yangFilesRootDir");
@@ -64,8 +65,8 @@ class YangToSourcesProcessor {
     }
 
     YangToSourcesProcessor(Log log, File yangFilesRootDir,
-            List<CodeGeneratorArg> codeGenerators, MavenProject project,
-            boolean inspectDependencies) {
+                           List<CodeGeneratorArg> codeGenerators, MavenProject project,
+                           boolean inspectDependencies) {
         this(log, yangFilesRootDir, codeGenerators, project,
                 inspectDependencies, new YangProvider());
     }
@@ -132,7 +133,7 @@ class YangToSourcesProcessor {
                 + "yang";
 
         void addYangsToMETA_INF(Log log, MavenProject project,
-                File yangFilesRootDir) throws MojoFailureException {
+                                File yangFilesRootDir) throws MojoFailureException {
             File targetYangDir = new File(project.getBasedir(), yangResourceDir);
 
             try {
@@ -151,7 +152,7 @@ class YangToSourcesProcessor {
         }
 
         private static void setResource(File targetYangDir, String targetPath,
-                MavenProject project) {
+                                        MavenProject project) {
             Resource res = new Resource();
             res.setDirectory(targetYangDir.getPath());
             if (targetPath != null)
@@ -198,7 +199,7 @@ class YangToSourcesProcessor {
      * Instantiate generator from class and call required method
      */
     private void generateSourcesWithOneGenerator(ContextHolder context,
-            CodeGeneratorArg codeGeneratorCfg) throws ClassNotFoundException,
+                                                 CodeGeneratorArg codeGeneratorCfg) throws ClassNotFoundException,
             InstantiationException, IllegalAccessException, IOException {
 
         codeGeneratorCfg.check();
index 357e6bab0bbc0715bb7fd10a41c38997128d4217..600e87d2679c8e2ad0cf3e2eb2481327631f21ca 100644 (file)
@@ -11,7 +11,6 @@ module controller-network {
        
 
        
-       
        typedef topology-id {
                type string;
        }
index 95b52a0a4a130bc0bc404a198c7f29fe8c0b6b0f..4520405bbebc615e71ef6749016d11c31e417a95 100644 (file)
@@ -228,6 +228,7 @@ public final class YangParserImpl implements YangModelParser {
             final YangLexer lexer = new YangLexer(input);
             final CommonTokenStream tokens = new CommonTokenStream(lexer);
             final YangParser parser = new YangParser(tokens);
+
             result = parser.yang();
         } catch (IOException e) {
             logger.warn("Exception while reading yang file: " + yangStream, e);
index 7d11db273b8a77d29e4b8eb3d263ebafa8b94f69..8361d4715631ff4e2afad6d7f588ba17c1b86027 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.controller.yang.parser.util;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.opendaylight.controller.yang.common.QName;
 import org.opendaylight.controller.yang.model.api.ModuleImport;
@@ -27,6 +28,9 @@ import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition
 import org.opendaylight.controller.yang.model.api.type.InstanceIdentifierTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.IntegerTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
+import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
+import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
 import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefinition;
@@ -76,7 +80,7 @@ public final class ParserUtils {
 
     /**
      * Get module import referenced by given prefix.
-     *
+     * 
      * @param builder
      *            module to search
      * @param prefix
@@ -97,7 +101,7 @@ public final class ParserUtils {
 
     /**
      * Parse uses path.
-     *
+     * 
      * @param usesPath
      *            as String
      * @return SchemaPath from given String
@@ -124,7 +128,7 @@ public final class ParserUtils {
 
     /**
      * Add all augment's child nodes to given target.
-     *
+     * 
      * @param augment
      * @param target
      */
@@ -133,54 +137,139 @@ public final class ParserUtils {
             final DataNodeContainerBuilder target) {
         for (DataSchemaNodeBuilder builder : augment.getChildNodes()) {
             builder.setAugmenting(true);
-            correctAugmentChildPath(augment, target.getPath());
+            correctAugmentChildPath(builder, target.getPath());
             target.addChildNode(builder);
         }
     }
 
     public static void fillAugmentTarget(
-            final AugmentationSchemaBuilder augment,
-            final ChoiceBuilder target) {
+            final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
         for (DataSchemaNodeBuilder builder : augment.getChildNodes()) {
             builder.setAugmenting(true);
-            correctAugmentChildPath(augment, target.getPath());
+            correctAugmentChildPath(builder, target.getPath());
             target.addChildNode(builder);
         }
     }
 
-    private static void correctAugmentChildPath(final DataNodeContainerBuilder node,
+    private static void correctAugmentChildPath(
+            final DataSchemaNodeBuilder childNode,
             final SchemaPath parentSchemaPath) {
-        for (DataSchemaNodeBuilder builder : node.getChildNodes()) {
-
-            // add correct path
-            List<QName> targetNodePath = new ArrayList<QName>(
-                    parentSchemaPath.getPath());
-            targetNodePath.add(builder.getQName());
-            builder.setPath(new SchemaPath(targetNodePath, true));
 
-            if (builder instanceof DataNodeContainerBuilder) {
-                DataNodeContainerBuilder cnb = (DataNodeContainerBuilder) builder;
-                correctAugmentChildPath(cnb, builder.getPath());
+        // set correct path
+        List<QName> targetNodePath = new ArrayList<QName>(
+                parentSchemaPath.getPath());
+        targetNodePath.add(childNode.getQName());
+        childNode.setPath(new SchemaPath(targetNodePath, true));
+
+        // set correct path for all child nodes
+        if (childNode instanceof DataNodeContainerBuilder) {
+            DataNodeContainerBuilder dataNodeContainer = (DataNodeContainerBuilder) childNode;
+            for (DataSchemaNodeBuilder child : dataNodeContainer
+                    .getChildNodes()) {
+                correctAugmentChildPath(child, childNode.getPath());
             }
+        }
 
-            // if child can contains type, correct path for this type too
-            if (builder instanceof TypeAwareBuilder) {
-                TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) builder;
-                QName nodeBuilderQName = nodeBuilder.getQName();
-                TypeDefinition<?> nodeBuilderType = nodeBuilder.getType();
-                if (nodeBuilderType != null) {
-                    TypeDefinition<?> newType = createCorrectTypeDefinition(
-                            parentSchemaPath, nodeBuilderQName, nodeBuilderType);
-                    nodeBuilder.setType(newType);
-                } else {
-                    TypeDefinitionBuilder nodeBuilderTypedef = nodeBuilder
-                            .getTypedef();
-                    SchemaPath newSchemaPath = createNewSchemaPath(
-                            nodeBuilderTypedef.getPath(), nodeBuilderQName,
-                            nodeBuilderTypedef.getQName());
-                    nodeBuilderTypedef.setPath(newSchemaPath);
+        // if node can contains type, correct path for this type too
+        if (childNode instanceof TypeAwareBuilder) {
+            TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) childNode;
+            correctTypeAwareNodePath(nodeBuilder, parentSchemaPath);
+        }
+    }
+
+    /**
+     * Repair schema path of node type.
+     * 
+     * @param node
+     *            node which contains type statement
+     * @param parentSchemaPath
+     *            schema path of parent node
+     */
+    private static void correctTypeAwareNodePath(
+            TypeAwareBuilder node, SchemaPath parentSchemaPath) {
+        final QName nodeBuilderQName = node.getQName();
+        final TypeDefinition<?> nodeType = node.getType();
+
+        Integer fd = null;
+        List<LengthConstraint> lengths = null;
+        List<PatternConstraint> patterns = null;
+        List<RangeConstraint> ranges = null;
+
+        if (nodeType != null) {
+            if (nodeType instanceof ExtendedType) {
+                ExtendedType et = (ExtendedType) nodeType;
+                if (nodeType
+                        .getQName()
+                        .getLocalName()
+                        .equals(nodeType.getBaseType().getQName()
+                                .getLocalName())) {
+                    fd = et.getFractionDigits();
+                    lengths = et.getLengths();
+                    patterns = et.getPatterns();
+                    ranges = et.getRanges();
+                    if (!hasConstraints(fd, lengths, patterns, ranges)) {
+                        return;
+                    }
                 }
             }
+            TypeDefinition<?> newType = createCorrectTypeDefinition(
+                    parentSchemaPath, nodeBuilderQName, nodeType);
+            node.setType(newType);
+        } else {
+            TypeDefinitionBuilder nodeBuilderTypedef = node.getTypedef();
+
+            fd = nodeBuilderTypedef.getFractionDigits();
+            lengths = nodeBuilderTypedef.getLengths();
+            patterns = nodeBuilderTypedef.getPatterns();
+            ranges = nodeBuilderTypedef.getRanges();
+
+            String tdbTypeName = nodeBuilderTypedef.getQName().getLocalName();
+            String baseTypeName = null;
+            if (nodeBuilderTypedef.getType() == null) {
+                baseTypeName = nodeBuilderTypedef.getTypedef().getQName()
+                        .getLocalName();
+            } else {
+                baseTypeName = nodeBuilderTypedef.getType().getQName()
+                        .getLocalName();
+            }
+            if (!(tdbTypeName.equals(baseTypeName))) {
+                return;
+            }
+
+            if (!hasConstraints(fd, lengths, patterns, ranges)) {
+                return;
+            }
+
+            SchemaPath newSchemaPath = createNewSchemaPath(
+                    nodeBuilderTypedef.getPath(), nodeBuilderQName,
+                    nodeBuilderTypedef.getQName());
+            nodeBuilderTypedef.setPath(newSchemaPath);
+        }
+    }
+
+    /**
+     * Check if there are some constraints.
+     * 
+     * @param fd
+     *            fraction digits
+     * @param lengths
+     *            length constraints
+     * @param patterns
+     *            pattern constraints
+     * @param ranges
+     *            range constraints
+     * @return true, if any of constraints are present, false otherwise
+     */
+    private static boolean hasConstraints(final Integer fd,
+            final List<LengthConstraint> lengths,
+            final List<PatternConstraint> patterns,
+            final List<RangeConstraint> ranges) {
+        if (fd == null && (lengths == null || lengths.isEmpty())
+                && (patterns == null || patterns.isEmpty())
+                && (ranges == null || ranges.isEmpty())) {
+            return false;
+        } else {
+            return true;
         }
     }
 
@@ -210,7 +299,8 @@ public final class ParserUtils {
                 DecimalTypeDefinition decimalType = (DecimalTypeDefinition) nodeType;
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, decimalType.getQName());
-                result = new Decimal64(newSchemaPath, decimalType.getFractionDigits());
+                result = new Decimal64(newSchemaPath,
+                        decimalType.getFractionDigits());
             } else if (nodeType instanceof EmptyTypeDefinition) {
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, nodeType.getQName());
@@ -254,8 +344,8 @@ public final class ParserUtils {
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, unionType.getQName());
                 return new UnionType(newSchemaPath, unionType.getTypes());
-            } else if(nodeType instanceof ExtendedType) {
-                ExtendedType extType = (ExtendedType)nodeType;
+            } else if (nodeType instanceof ExtendedType) {
+                ExtendedType extType = (ExtendedType) nodeType;
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, extType.getQName());
                 result = createNewExtendedType(newSchemaPath, extType);
@@ -270,7 +360,8 @@ public final class ParserUtils {
         TypeDefinition<?> baseType = oldExtendedType.getBaseType();
         String desc = oldExtendedType.getDescription();
         String ref = oldExtendedType.getReference();
-        ExtendedType.Builder builder = new ExtendedType.Builder(qname, baseType, desc, ref, newSchemaPath);
+        ExtendedType.Builder builder = new ExtendedType.Builder(qname,
+                baseType, desc, ref, newSchemaPath);
         builder.status(oldExtendedType.getStatus());
         builder.lengths(oldExtendedType.getLengths());
         builder.patterns(oldExtendedType.getPatterns());
@@ -559,9 +650,9 @@ public final class ParserUtils {
      * <li>reference</li>
      * <li>config</li>
      * </ul>
-     *
+     * 
      * These parameters may be refined for any node.
-     *
+     * 
      * @param node
      *            node to refine
      * @param refine
index 733b524cd3656ce5b3830a346eae862ee960db30..ba31e51922a62c2d3fc6b352a2e3aa8110d3d216 100644 (file)
@@ -848,14 +848,20 @@ public class YangParserTest {
         Leafref ifcIdType = (Leafref) ifcId.getType();
         SchemaPath ifcIdTypeSchemaPath = ifcIdType.getPath();
         List<QName> ifcIdTypePath = ifcIdTypeSchemaPath.getPath();
-        QName q0 = new QName(new URI("urn:simple.types.data.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "interfaces");
-        QName q1 = new QName(new URI("urn:simple.types.data.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "ifEntry");
-        QName q2 = new QName(new URI("urn:simple.container.demo.test"),
-                simpleDateFormat.parse("2013-02-27"), "data", "augment-holder");
-        QName q3 = new QName(new URI("urn:simple.container.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "interface-id");
+        
+        URI types1URI = URI.create("urn:simple.container.demo");
+        URI types2URI = URI.create("urn:simple.types.data.demo");
+        URI types3URI = URI.create("urn:simple.container.demo.test");
+        Date expectedDate = simpleDateFormat.parse("2013-02-27");
+        
+        QName q0 = new QName(types2URI,
+                expectedDate, "data", "interfaces");
+        QName q1 = new QName(types2URI,
+                expectedDate, "data", "ifEntry");
+        QName q2 = new QName(types3URI,
+                expectedDate, "data", "augment-holder");
+        QName q3 = new QName(types1URI,
+                expectedDate, "data", "interface-id");
         assertEquals(q0, ifcIdTypePath.get(0));
         assertEquals(q1, ifcIdTypePath.get(1));
         assertEquals(q2, ifcIdTypePath.get(2));
@@ -869,9 +875,18 @@ public class YangParserTest {
         assertEquals(q0, higherLayerTypePath.get(0));
         assertEquals(q1, higherLayerTypePath.get(1));
         assertEquals(q2, higherLayerTypePath.get(2));
-        q3 = new QName(new URI("urn:simple.container.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "higher-layer-if");
+        q3 = new QName(types1URI,
+                expectedDate, "data", "higher-layer-if");
         assertEquals(q3, higherLayerTypePath.get(3));
+        
+        LeafSchemaNode myType = (LeafSchemaNode) augment
+                .getDataChildByName("my-type");
+        ExtendedType leafType = (ExtendedType)myType.getType();
+        
+        testModule = TestUtils.findModule(modules, "types2");
+        TypeDefinition<?> typedef = TestUtils.findTypedef(testModule.getTypeDefinitions(), "my-type1");
+        
+        assertEquals(typedef, leafType);
     }
 
     @Test
index 4ec69c18b229bb7bc4055bf7140b526c0378da2f..3dbfa780a3527641933e1dae3e77c237822bbe47 100644 (file)
@@ -123,6 +123,9 @@ module types1 {
                 path "/if:interfaces/if:interface/if:higher-layer-if";
             }
         }
+        leaf my-type {
+            type data:my-type1;
+        }
     }
     
     container mycont {
index cdf867489388ba4d087d1345649e59bc112c1500..004a2a49523a5ad7dd643b9b48173dc777337e19 100644 (file)
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
  * \r
  * \r
  */\r
-public class QName {\r
+public final class QName {\r
     protected static final Logger logger = LoggerFactory\r
         .getLogger(QName.class);\r
 \r
index 86bde24d62d8131314f0f1d37b7e8ed61552f72e..e5ef2026f17e9bb200dec87cecad2d70baeed396 100644 (file)
@@ -194,126 +194,54 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
     }
 
     @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result
-                + ((baseType == null) ? 0 : baseType.hashCode());
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
-        result = prime * result
-                + ((description == null) ? 0 : description.hashCode());
-        result = prime
-                * result
-                + ((unknownSchemaNodes == null) ? 0 : unknownSchemaNodes
-                        .hashCode());
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
-        result = prime * result
-                + ((reference == null) ? 0 : reference.hashCode());
-        result = prime * result + ((status == null) ? 0 : status.hashCode());
-        result = prime * result
-                + ((typeName == null) ? 0 : typeName.hashCode());
-        result = prime * result + ((units == null) ? 0 : units.hashCode());
-        return result;
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
+    public boolean equals(Object o) {
+        if (this == o) {
             return true;
         }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        ExtendedType other = (ExtendedType) obj;
-        if (baseType == null) {
-            if (other.baseType != null) {
-                return false;
-            }
-        } else if (!baseType.equals(other.baseType)) {
-            return false;
-        }
-        if (defaultValue == null) {
-            if (other.defaultValue != null) {
-                return false;
-            }
-        } else if (!defaultValue.equals(other.defaultValue)) {
-            return false;
-        }
-        if (description == null) {
-            if (other.description != null) {
-                return false;
-            }
-        } else if (!description.equals(other.description)) {
-            return false;
-        }
-        if (unknownSchemaNodes == null) {
-            if (other.unknownSchemaNodes != null) {
-                return false;
-            }
-        } else if (!unknownSchemaNodes.equals(other.unknownSchemaNodes)) {
+        if (!(o instanceof ExtendedType)) {
             return false;
         }
-        if (path == null) {
-            if (other.path != null) {
-                return false;
-            }
-        } else if (!path.equals(other.path)) {
-            return false;
-        }
-        if (reference == null) {
-            if (other.reference != null) {
-                return false;
-            }
-        } else if (!reference.equals(other.reference)) {
-            return false;
-        }
-        if (status != other.status) {
-            return false;
-        }
-        if (typeName == null) {
-            if (other.typeName != null) {
-                return false;
-            }
-        } else if (!typeName.equals(other.typeName)) {
+
+        ExtendedType that = (ExtendedType) o;
+        if (path != null ? !path.equals(that.path) : that.path != null) {
             return false;
         }
-        if (units == null) {
-            if (other.units != null) {
-                return false;
-            }
-        } else if (!units.equals(other.units)) {
+        if (typeName != null ? !typeName.equals(that.typeName) : that.typeName != null)
             return false;
-        }
+
         return true;
     }
 
+    @Override
+    public int hashCode() {
+        int result = typeName != null ? typeName.hashCode() : 0;
+        result = 31 * result + (path != null ? path.hashCode() : 0);
+        return result;
+    }
+
     @Override
     public String toString() {
-        StringBuilder builder2 = new StringBuilder();
-        builder2.append("ExtendedType [typeName=");
-        builder2.append(typeName);
-        builder2.append(", baseType=");
-        builder2.append(baseType);
-        builder2.append(", path=");
-        builder2.append(path);
-        builder2.append(", description=");
-        builder2.append(description);
-        builder2.append(", reference=");
-        builder2.append(reference);
-        builder2.append(", unknownSchemaNodes=");
-        builder2.append(unknownSchemaNodes);
-        builder2.append(", status=");
-        builder2.append(status);
-        builder2.append(", units=");
-        builder2.append(units);
-        builder2.append(", defaultValue=");
-        builder2.append(defaultValue);
-        builder2.append("]");
-        return builder2.toString();
+        StringBuilder builder = new StringBuilder();
+        builder.append("ExtendedType [typeName=");
+        builder.append(typeName);
+        builder.append(", baseType=");
+        builder.append(baseType);
+        builder.append(", path=");
+        builder.append(path);
+        builder.append(", description=");
+        builder.append(description);
+        builder.append(", reference=");
+        builder.append(reference);
+        builder.append(", unknownSchemaNodes=");
+        builder.append(unknownSchemaNodes);
+        builder.append(", status=");
+        builder.append(status);
+        builder.append(", units=");
+        builder.append(units);
+        builder.append(", defaultValue=");
+        builder.append(defaultValue);
+        builder.append("]");
+        return builder.toString();
     }
 
     public List<RangeConstraint> getRanges() {
index 2d6a78988752de136af601dd70ab40713cfa9a9e..13c2ba7cb55455800e763c754f53883d8e0986eb 100644 (file)
@@ -33,7 +33,7 @@ public final class SchemaContextUtil {
     public static DataSchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
         if (schemaPath != null) {
             final Module module = resolveModuleFromSchemaPath(context, schemaPath);
-            final Queue<QName> prefixedPath = new LinkedList<QName>(schemaPath.getPath());
+            final Queue<QName> prefixedPath = new LinkedList<>(schemaPath.getPath());
 
             if ((module != null) && (prefixedPath != null)) {
                 return findSchemaNodeForGivenPath(context, module, prefixedPath);
@@ -87,32 +87,35 @@ public final class SchemaContextUtil {
         return null;
     }
 
-    public static Module resolveModuleFromSchemaPath(final SchemaContext context, final SchemaPath schemaPath) {
+    private static Module resolveModuleFromSchemaPath(final SchemaContext
+        context, final SchemaPath schemaPath) {
         if ((schemaPath != null) && (schemaPath.getPath() != null)) {
-            List<QName> path = schemaPath.getPath();
-            final QName qname = path.get(path.size()-1);
+            final List<QName> path = schemaPath.getPath();
+            if (!path.isEmpty()) {
+                final QName qname = path.get(path.size() - 1);
 
-            if ((qname != null) && (qname.getNamespace() != null)) {
-                return context.findModuleByNamespace(qname.getNamespace());
+                if ((qname != null) && (qname.getNamespace() != null)) {
+                    return context.findModuleByNamespace(qname.getNamespace());
+                }
             }
         }
         return null;
     }
 
-    public static Module resolveModuleFromTypePath(final SchemaContext context, final TypeDefinition<?> type) {
+    public static Module findParentModuleForTypeDefinition(
+            final SchemaContext context, final TypeDefinition<?> type) {
         final SchemaPath schemaPath = type.getPath();
         if ((schemaPath != null) && (schemaPath.getPath() != null)) {
             if(type instanceof ExtendedType) {
                 List<QName> path = schemaPath.getPath();
-                final QName qname = path.get(path.size()-1);
+                final QName qname = path.get(path.size() - 1);
 
                 if ((qname != null) && (qname.getNamespace() != null)) {
                     return context.findModuleByNamespace(qname.getNamespace());
                 }
             } else {
-                LinkedList<QName> path = new LinkedList<QName>(schemaPath.getPath());
-                path.removeLast();
-                final QName qname = path.get(path.size()-1);
+                List<QName> path = schemaPath.getPath();
+                final QName qname = path.get(path.size() - 2);
 
                 if ((qname != null) && (qname.getNamespace() != null)) {
                     return context.findModuleByNamespace(qname.getNamespace());
@@ -142,7 +145,7 @@ public final class SchemaContextUtil {
                     "The Schema Path MUST contain at least ONE QName which defines namespace and Local name" +
                     "of path.");
         }
-        final QName qname = qnamedPath.get(0);
+        final QName qname = qnamedPath.get(qnamedPath.size() - 1);
         return context.findModuleByNamespace(qname.getNamespace());
     }
 
@@ -186,7 +189,7 @@ public final class SchemaContextUtil {
 
     private static Queue<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
             final String xpath) {
-        final Queue<QName> path = new LinkedList<QName>();
+        final Queue<QName> path = new LinkedList<>();
         if (xpath != null) {
             final String[] prefixedPath = xpath.split("/");
 
@@ -240,7 +243,7 @@ public final class SchemaContextUtil {
     private static Queue<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
             final RevisionAwareXPath relativeXPath,
             final SchemaPath leafrefSchemaPath) {
-        final Queue<QName> absolutePath = new LinkedList<QName>();
+        final Queue<QName> absolutePath = new LinkedList<>();
 
         if ((module != null) && (relativeXPath != null) && !relativeXPath.isAbsolute()
                 && (leafrefSchemaPath != null)) {
index ed23b5f067c45ebd000ac52fffc919e9707800ef..85a97f0b852e99fa728ab4366e69e8dda775dd93 100644 (file)
@@ -267,6 +267,18 @@ public interface IUserManager extends UserDetailsService {
      */
     public ISessionManager getSessionManager();
 
+    /**
+     * Checks if the specified role belongs to any application. Usually an
+     * application will call this function when configuring a role, to check if
+     * that role is already being used by another application.
+     *
+     * @param role
+     *            The role to check
+     * @return true if the specified role belongs to any application or if the
+     *         role is a well-known controller role, false otherwise.
+     */
+    public boolean isRoleInUse(String role);
+
     /* non-Javadoc
      * Returns the password for a given user
      *
index 5ddf6be6c54914e9f0cf0047c0dd272ea7813590..e835887606273ce478ae0cdc63c534b9bab8c253 100644 (file)
@@ -156,9 +156,9 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
                     "usermanager.authorizationSaveConfigEvent",
                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
         } catch (CacheConfigException cce) {
-            logger.error("\nCache configuration invalid - check cache mode");
+            logger.error("Cache configuration invalid - check cache mode");
         } catch (CacheExistException ce) {
-            logger.error("\nCache already exits - destroy and recreate if needed");
+            logger.debug("Skipping cache creation as already present");
         }
     }
 
@@ -172,43 +172,43 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
         activeUsers = (ConcurrentMap<String, AuthenticatedUser>) clusterGlobalService
                 .getCache("usermanager.activeUsers");
         if (activeUsers == null) {
-            logger.error("\nFailed to get cache for activeUsers");
+            logger.error("Failed to get cache for activeUsers");
         }
 
         localUserConfigList = (ConcurrentMap<String, UserConfig>) clusterGlobalService
                 .getCache("usermanager.localUserConfigList");
         if (localUserConfigList == null) {
-            logger.error("\nFailed to get cache for localUserConfigList");
+            logger.error("Failed to get cache for localUserConfigList");
         }
 
         remoteServerConfigList = (ConcurrentMap<String, ServerConfig>) clusterGlobalService
                 .getCache("usermanager.remoteServerConfigList");
         if (remoteServerConfigList == null) {
-            logger.error("\nFailed to get cache for remoteServerConfigList");
+            logger.error("Failed to get cache for remoteServerConfigList");
         }
 
         authorizationConfList = (ConcurrentMap<String, AuthorizationConfig>) clusterGlobalService
                 .getCache("usermanager.authorizationConfList");
         if (authorizationConfList == null) {
-            logger.error("\nFailed to get cache for authorizationConfList");
+            logger.error("Failed to get cache for authorizationConfList");
         }
 
         localUserListSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.localUserSaveConfigEvent");
         if (localUserListSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for localUserSaveConfigEvent");
+            logger.error("Failed to get cache for localUserSaveConfigEvent");
         }
 
         remoteServerSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.remoteServerSaveConfigEvent");
         if (remoteServerSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for remoteServerSaveConfigEvent");
+            logger.error("Failed to get cache for remoteServerSaveConfigEvent");
         }
 
         authorizationSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.authorizationSaveConfigEvent");
         if (authorizationSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for authorizationSaveConfigEvent");
+            logger.error("Failed to get cache for authorizationSaveConfigEvent");
         }
     }
 
@@ -866,29 +866,29 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     @Override
     public List<String> getUserRoles(String userName) {
-        if (userName == null) {
-            return new ArrayList<String>(0);
+        List<String> roles = null;
+        if (userName != null) {
+            /*
+             * First look in active users then in local configured users,
+             * finally in local authorized users
+             */
+            if (activeUsers.containsKey(userName)) {
+                roles = activeUsers.get(userName).getUserRoles();
+            } else if (localUserConfigList.containsKey(userName)) {
+                roles = localUserConfigList.get(userName).getRoles();
+            } else if (authorizationConfList.containsKey(userName)) {
+                roles = authorizationConfList.get(userName).getRoles();
+            }
         }
-        AuthenticatedUser locatedUser = activeUsers.get(userName);
-        return (locatedUser == null) ? new ArrayList<String>(0) : locatedUser
-                .getUserRoles();
+        return (roles == null) ? new ArrayList<String>(0) : roles;
     }
 
     @Override
     public UserLevel getUserLevel(String username) {
-        // Returns the controller well-know user level for the passed user
-        List<String> rolesNames = null;
-
-        // First check in active users then in local configured users
-        if (activeUsers.containsKey(username)) {
-            List<String> roles = activeUsers.get(username).getUserRoles();
-            rolesNames = (roles == null || roles.isEmpty()) ? null : roles;
-        } else if (localUserConfigList.containsKey(username)) {
-            UserConfig config = localUserConfigList.get(username);
-            rolesNames = (config == null) ? null : config.getRoles();
-        }
+        // Returns the highest controller user level for the passed user
+        List<String> rolesNames = getUserRoles(username);
 
-        if (rolesNames == null) {
+        if (rolesNames.isEmpty()) {
             return UserLevel.NOUSER;
         }
 
@@ -926,19 +926,11 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     @Override
     public List<UserLevel> getUserLevels(String username) {
-        // Returns the controller well-know user levels for the passed user
-        List<String> rolesNames = null;
+        // Returns the controller user levels for the passed user
+        List<String> rolesNames =  getUserRoles(username);
         List<UserLevel> levels = new ArrayList<UserLevel>();
 
-        if (activeUsers.containsKey(username)) {
-            List<String> roles = activeUsers.get(username).getUserRoles();
-            rolesNames = (roles == null || roles.isEmpty()) ? null : roles;
-        } else if (localUserConfigList.containsKey(username)) {
-            UserConfig config = localUserConfigList.get(username);
-            rolesNames = (config == null) ? null : config.getRoles();
-        }
-
-        if (rolesNames == null) {
+        if (rolesNames.isEmpty()) {
             return levels;
         }
 
@@ -1075,7 +1067,7 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     }
 
-    // following are setters for use in unit testing
+    // Following are setters for use in unit testing
     void setLocalUserConfigList(ConcurrentMap<String, UserConfig> ucl) {
         if (ucl != null) {
             this.localUserConfigList = ucl;
@@ -1119,4 +1111,32 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
     public String getPassword(String username) {
         return localUserConfigList.get(username).getPassword();
     }
+
+    @Override
+    public boolean isRoleInUse(String role) {
+        if (role == null || role.isEmpty()) {
+            return false;
+        }
+        // Check against controller roles
+        if (role.equals(UserLevel.SYSTEMADMIN.toString())
+                || role.equals(UserLevel.NETWORKADMIN.toString())
+                || role.equals(UserLevel.NETWORKOPERATOR.toString())) {
+            return true;
+        }
+        // Check if container roles
+        if (containerAuthorizationClient != null) {
+            if (containerAuthorizationClient.isApplicationRole(role)) {
+                return true;
+            }
+        }
+        // Finally if application role
+        if (applicationAuthorizationClients != null) {
+            for (IResourceAuthorization client : this.applicationAuthorizationClients) {
+                if (client.isApplicationRole(role)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
 }
index 626011bd695fc0288f9a064ac682df75cea17e8b..df421e4fe6c2a017c656ce70e93327b2175abec9 100644 (file)
@@ -55,14 +55,17 @@ public class UserManagerImplTest {
                         // Server config can't be empty
                         static final long serialVersionUID = 8645L;
 
+                        @Override
                         public String getAddress() {
                             return "1.1.1.1";
                         }
 
+                        @Override
                         public String getSecret() {
                             return "secret";
                         }
 
+                        @Override
                         public String getProtocol() {
                             return "IPv4";
                         }
@@ -80,11 +83,21 @@ public class UserManagerImplTest {
                             "7029,7455,8165,7029,7881", roles));
                 }
             });
+
+            um.setAuthorizationConfList(new ConcurrentHashMap<String, AuthorizationConfig>() {
+                static final long serialVersionUID = 2L;
+                {
+                    List<String> roles = new ArrayList<String>(3);
+                    roles.add(UserLevel.NETWORKOPERATOR.toString());
+                    roles.add("Container1-Admin");
+                    roles.add("Application2-User");
+
+                    put("Andrew", new AuthorizationConfig("Andrew", roles));
+                }
+            });
             // instantiate an empty activeUser collection
             um.setActiveUsers(new ConcurrentHashMap<String, AuthenticatedUser>());
-
         }
-
     }
 
     /**
@@ -97,11 +110,13 @@ public class UserManagerImplTest {
         // instantiate an anonymous AAAProvider
         IAAAProvider a3p = new IAAAProvider() {
 
+            @Override
             public AuthResponse authService(String userName, String password,
                     String server, String secretKey) {
                 return new AuthResponse();
             };
 
+            @Override
             public String getName() {
                 return "dummyAAAProvider";
             }
@@ -254,6 +269,9 @@ public class UserManagerImplTest {
         Assert.assertTrue(um.getUserLevel("Jack") == UserLevel.SYSTEMADMIN);
         // Run the check on configured users
         Assert.assertTrue(um.getUserLevel("John") == UserLevel.NETWORKOPERATOR);
-        Assert.assertTrue(um.getUserLevel("Andrew") == UserLevel.NOUSER);
+        // Run the check on local authorized users
+        Assert.assertTrue(um.getUserLevel("Andrew") == UserLevel.NETWORKOPERATOR);
+        // Non locally known user
+        Assert.assertTrue(um.getUserLevel("Tom") == UserLevel.NOUSER);
     }
 }