Merge "fix maven warnings regarding missing versions of some plugins"
authorGiovanni Meo <gmeo@cisco.com>
Thu, 18 Jul 2013 08:02:01 +0000 (08:02 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 18 Jul 2013 08:02:01 +0000 (08:02 +0000)
55 files changed:
opendaylight/commons/opendaylight/pom.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini
opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.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/TypeProviderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/ExtendedTypedefTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/typedef_of_typedef.yang [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/ClassCodeGenerator.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/samples/maven-code-gen-sample/src/main/yang/typedef_of_typedef.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractBuilder.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractDataNodeContainerBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractTypeAwareBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/Builder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/AnyXmlBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/AugmentationSchemaBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ChoiceBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ChoiceCaseBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ConstraintsBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ContainerSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/DeviationBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ExtensionBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/FeatureBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/GroupingBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/IdentitySchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/IdentityrefTypeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/LeafListSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/LeafSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ListSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ModuleBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/NotificationBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/RpcDefinitionBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/TypeDefinitionBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/UnionTypeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/UnknownSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/UsesNodeBuilderImpl.java
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/impl/YangParserListenerImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/ParserListenerUtils.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/main/java/org/opendaylight/controller/yang/parser/util/RefineHolder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/RefineUtils.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/TypeConstraints.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/YangParseException.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserNegativeTest.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/types.yang
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment0.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment1.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment2.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/yang/yang-data-impl/src/test/java/org/opendaylight/controller/yang/data/impl/NodeUtilsTest.java
opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerImpl.java

index 98e1d1ab909e945c30f75d3db67bfdb43d4bb654..33218808a84773e0a6b884eee204a1193763c8c3 100644 (file)
@@ -40,6 +40,7 @@
     <virgo.version>3.6.0.RELEASE</virgo.version>
     <geminiweb.version>2.2.0.RELEASE</geminiweb.version>
     <checkstyle.version>2.10</checkstyle.version>
+    <testvm.argLine>-Xmx1024m -XX:MaxPermSize=256m</testvm.argLine>
   </properties>
 
   <pluginRepositories>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-failsafe-plugin</artifactId>
         <version>${failsafe.version}</version>
+        <configuration>
+          <argLine>${testvm.argLine}</argLine>
+        </configuration>
         <executions>
           <execution>
             <goals>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>${surefire.version}</version>
+        <configuration>
+          <argLine>${testvm.argLine}</argLine>
+        </configuration>
       </plugin>
     </plugins>
     <pluginManagement>
index 460145ee8729d949dd6b0ef664be74d7947dd3ac..6e8a3555234ef8cd668a048fd299eddac823656e 100644 (file)
@@ -57,15 +57,17 @@ org.eclipse.gemini.web.tomcat.config.path=configuration/tomcat-server.xml
 # The description statistics polling interval in second (default 60 sec)
 # of.descStatsPollInterval=60
 # The table statistics polling interval in second (default 10 sec)
-#  of.tableStatsPollInterval=10
+# of.tableStatsPollInterval=10
 # The maximum number of asynchronous messages can be sent before sending a Barrier Request (default 100)
 # of.barrierMessagePriorCount=100
 # The interval which determines how often the discovery packets should be sent (default 300 sec)
 # of.discoveryInterval=300
-# The timeout value in waiting for returned discovery packet (default 60 sec)
-# of.discoveryTimeout=60
-# The number of retries after the initial discovery packet is not received within the timeout period (default 2)
-# of.discoveryRetry=2
+# The timeout multiple of discovery interval
+# of.discoveryTimeoutMultiple=2
+# For newly added ports, allow one more retry if the elapsed time exceeds this threshold (default 10 sec)
+# of.discoveryThreshold=10
+# The maximum number of ports handled in one discovery batch (default 1024)
+# of.discoveryBatchMaxPorts=1024
 
 # TLS configuration
 # To enable TLS, set secureChannelEnabled=true and specify the location of controller Java KeyStore and TrustStore files.
index eea28364ac9cc4e5db00c76a67dee5e9873a918c..2eaafb698917d74225866068b385ec8a3f74aeba 100644 (file)
@@ -897,10 +897,11 @@ public class ForwardingRulesManager implements IForwardingRulesManager, PortGrou
             log.warn(logMsg, groupName);
             return new Status(StatusCode.NOTACCEPTABLE, msg);
         }
-        int toBeRemoved = groupFlows.get(groupName).size();
+        int toBeRemoved = 0;
         String error = "";
         if (groupFlows.containsKey(groupName)) {
             List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
+            toBeRemoved = list.size();
             for (FlowEntryInstall entry : list) {
                 Status status = this.removeEntry(entry.getOriginal(), false);
                 if (status.isSuccess()) {
index 3f3c8bde2e2aef4751c735f84e6259da1b10c730..ebd5a68341b9caa5cc3166f415c3d0ed212d8bf4 100644 (file)
@@ -11,6 +11,7 @@ package org.opendaylight.controller.protocol_plugin.openflow.internal;
 import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -70,20 +71,23 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     private IDiscoveryListener discoveryListener = null;
     private IInventoryProvider inventoryProvider = null;
     private IDataPacketMux iDataPacketMux = null;
-    // Newly added ports go into this list and will be served first
+    // High priority list containing newly added ports which will be served first
     private List<NodeConnector> readyListHi = null;
-    // Come here after served at least once
+    // List containing all the ports which will be served periodically
     private List<NodeConnector> readyListLo = null;
     // Staging area during quiet period
-    private List<NodeConnector> waitingList = null;
+    private List<NodeConnector> stagingList = null;
     // Wait for next discovery packet. The map contains the time elapsed since
     // the last received LLDP frame on each node connector
-    private ConcurrentMap<NodeConnector, Integer> pendingMap = null;
-    // openflow edges keyed by head connector
+    private ConcurrentMap<NodeConnector, Integer> holdTime = null;
+    // Allow one more retry for newly added ports. This map contains the time
+    // period elapsed since last discovery pkt transmission on the port.
+    private ConcurrentMap<NodeConnector, Integer> elapsedTime = null;
+    // OpenFlow edges keyed by head connector
     private ConcurrentMap<NodeConnector, Edge> edgeMap = null;
-    // Aging entries keyed by head edge connector
+    // The map contains aging entry keyed by head connector of Production edge
     private ConcurrentMap<NodeConnector, Integer> agingMap = null;
-    // Production edges keyed by head edge connector
+    // Production edges keyed by head connector
     private ConcurrentMap<NodeConnector, Edge> prodMap = null;
 
     private Timer discoveryTimer;
@@ -91,21 +95,20 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     private final static long discoveryTimerTick = 2L * 1000; // per tick in msec
     private int discoveryTimerTickCount = 0; // main tick counter
     // Max # of ports handled in one batch
-    private int discoveryBatchMaxPorts = 500;
+    private int discoveryBatchMaxPorts;
     // Periodically restart batching process
-    private int discoveryBatchRestartTicks = getDiscoveryInterval();
-    private int discoveryBatchPausePeriod = 5;
+    private int discoveryBatchRestartTicks;
+    private int discoveryBatchPausePeriod = 2;
     // Pause after this point
-    private int discoveryBatchPauseTicks = discoveryBatchRestartTicks - discoveryBatchPausePeriod;
-    // Number of retries after initial timeout
-    private int discoveryRetry = getDiscoveryRetry();
-    private int discoveryTimeoutTicks = getDiscoveryTimeout();
-    private int discoveryAgeoutTicks = getDiscoveryAgeout();
+    private int discoveryBatchPauseTicks;
+    private int discoveryTimeoutTicks;
+    private int discoveryThresholdTicks;
+    private int discoveryAgeoutTicks;
     // multiple of discoveryBatchRestartTicks
     private int discoveryConsistencyCheckMultiple = 2;
     // CC tick counter
-    private int discoveryConsistencyCheckTickCount = discoveryBatchPauseTicks;
-    // # of times CC getscalled
+    private int discoveryConsistencyCheckTickCount;
+    // # of times CC gets called
     private int discoveryConsistencyCheckCallingTimes = 0;
     // # of cases CC corrected
     private int discoveryConsistencyCheckCorrected = 0;
@@ -162,9 +165,9 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     }
 
     public enum DiscoveryPeriod {
-        INTERVAL(300),
-        TIMEOUT (60),
-        AGEOUT  (120);
+        INTERVAL        (300),
+        AGEOUT          (120),
+        THRESHOLD       (10);
 
         private int time;   // sec
         private int tick;   // tick
@@ -187,9 +190,18 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
             return tick;
         }
 
+        public void setTick(int tick) {
+            this.time = tick2Time(tick);
+            this.tick = tick;
+        }
+
         private int time2Tick(int time) {
             return (int) (time / (discoveryTimerTick / 1000));
         }
+
+        private int tick2Time(int tick) {
+            return (int) (tick * (discoveryTimerTick / 1000));
+        }
     }
 
     private RawPacket createDiscoveryPacket(NodeConnector nodeConnector) {
@@ -409,7 +421,6 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
             logger.error("Caught exception ", e);
         }
         addEdge(edge, props);
-        pendingMap.put(dstNodeConnector, 0);
 
         logger.trace("Received discovery packet for Edge {}", edge);
 
@@ -472,11 +483,11 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
             return true;
         }
 
-        if (pendingMap.keySet().contains(nodeConnector)) {
+        if (holdTime.keySet().contains(nodeConnector)) {
             return true;
         }
 
-        if (waitingList.contains(nodeConnector)) {
+        if (stagingList.contains(nodeConnector)) {
             return true;
         }
 
@@ -494,6 +505,9 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
 
             workingSet.add(nodeConnector);
             removeSet.add(nodeConnector);
+
+            // Put it in the map and start the timer. It may need retry.
+            elapsedTime.put(nodeConnector, 0);
         }
         readyListHi.removeAll(removeSet);
 
@@ -572,12 +586,12 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         removeSet = getRemoveSet(readyListLo, node);
         readyListLo.removeAll(removeSet);
 
-        removeSet = getRemoveSet(waitingList, node);
-        waitingList.removeAll(removeSet);
+        removeSet = getRemoveSet(stagingList, node);
+        stagingList.removeAll(removeSet);
 
-        removeSet = getRemoveSet(pendingMap.keySet(), node);
+        removeSet = getRemoveSet(holdTime.keySet(), node);
         for (NodeConnector nodeConnector : removeSet) {
-            pendingMap.remove(nodeConnector);
+            holdTime.remove(nodeConnector);
         }
 
         removeSet = getRemoveSet(edgeMap.keySet(), node);
@@ -594,28 +608,25 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     private void removeDiscovery(NodeConnector nodeConnector) {
         readyListHi.remove(nodeConnector);
         readyListLo.remove(nodeConnector);
-        waitingList.remove(nodeConnector);
-        pendingMap.remove(nodeConnector);
+        stagingList.remove(nodeConnector);
+        holdTime.remove(nodeConnector);
         removeEdge(nodeConnector, false);
         removeProdEdge(nodeConnector);
     }
 
     private void checkTimeout() {
         Set<NodeConnector> removeSet = new HashSet<NodeConnector>();
-        Set<NodeConnector> retrySet = new HashSet<NodeConnector>();
         int ticks;
 
-        Set<NodeConnector> pendingSet = pendingMap.keySet();
-        if (pendingSet != null) {
-            for (NodeConnector nodeConnector : pendingSet) {
-                ticks = pendingMap.get(nodeConnector);
-                pendingMap.put(nodeConnector, ++ticks);
-                if (ticks > getDiscoveryFinalTimeoutInterval()) {
+        Set<NodeConnector> monitorSet = holdTime.keySet();
+        if (monitorSet != null) {
+            for (NodeConnector nodeConnector : monitorSet) {
+                ticks = holdTime.get(nodeConnector);
+                holdTime.put(nodeConnector, ++ticks);
+                if (ticks >= discoveryTimeoutTicks) {
                     // timeout the edge
                     removeSet.add(nodeConnector);
                     logger.trace("Discovery timeout {}", nodeConnector);
-                } else if (ticks % discoveryTimeoutTicks == 0) {
-                    retrySet.add(nodeConnector);
                 }
             }
         }
@@ -624,8 +635,22 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
             removeEdge(nodeConnector);
         }
 
-        for (NodeConnector nodeConnector : retrySet) {
-            transmitQ.add(nodeConnector);
+        Set<NodeConnector> retrySet = new HashSet<NodeConnector>();
+        Set<NodeConnector> ncSet = elapsedTime.keySet();
+        if ((ncSet != null) && (ncSet.size() > 0)) {
+            for (NodeConnector nodeConnector : ncSet) {
+                ticks = elapsedTime.get(nodeConnector);
+                elapsedTime.put(nodeConnector, ++ticks);
+                if (ticks >= discoveryThresholdTicks) {
+                    retrySet.add(nodeConnector);
+                }
+            }
+
+            for (NodeConnector nodeConnector : retrySet) {
+                // Allow one more retry
+                readyListLo.add(nodeConnector);
+                elapsedTime.remove(nodeConnector);
+            }
         }
     }
 
@@ -659,15 +684,19 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         if (++discoveryTimerTickCount <= discoveryBatchPauseTicks) {
             for (NodeConnector nodeConnector : getWorkingSet()) {
                 transmitQ.add(nodeConnector);
+                // Move to staging area after it's served
+                if (!stagingList.contains(nodeConnector)) {
+                    stagingList.add(nodeConnector);
+                }
             }
         } else if (discoveryTimerTickCount >= discoveryBatchRestartTicks) {
             discoveryTimerTickCount = 0;
-            for (NodeConnector nodeConnector : waitingList) {
+            for (NodeConnector nodeConnector : stagingList) {
                 if (!readyListLo.contains(nodeConnector)) {
                     readyListLo.add(nodeConnector);
                 }
             }
-            waitingList.removeAll(readyListLo);
+            stagingList.removeAll(readyListLo);
         }
     }
 
@@ -696,7 +725,7 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
             }
 
             if (!isTracked(nodeConnector)) {
-                waitingList.add(nodeConnector);
+                stagingList.add(nodeConnector);
                 discoveryConsistencyCheckCorrected++;
                 logger.debug("ConsistencyChecker: add back untracked {}", nodeConnector);
                 continue;
@@ -709,14 +738,14 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
 
         // remove stale entries
         removeSet.clear();
-        for (NodeConnector nodeConnector : waitingList) {
+        for (NodeConnector nodeConnector : stagingList) {
             if (!isEnabled(nodeConnector)) {
                 removeSet.add(nodeConnector);
                 discoveryConsistencyCheckCorrected++;
                 logger.debug("ConsistencyChecker: remove disabled {}", nodeConnector);
             }
         }
-        waitingList.removeAll(removeSet);
+        stagingList.removeAll(removeSet);
 
         // Get a snapshot of all the existing switches
         Map<Long, ISwitch> switches = this.controller.getSwitches();
@@ -725,7 +754,7 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
                 Node node = NodeCreator.createOFNode(sw.getId());
                 NodeConnector nodeConnector = NodeConnectorCreator.createOFNodeConnector(port.getPortNumber(), node);
                 if (!isTracked(nodeConnector)) {
-                    waitingList.add(nodeConnector);
+                    stagingList.add(nodeConnector);
                     discoveryConsistencyCheckCorrected++;
                     logger.debug("ConsistencyChecker: add back untracked {}", nodeConnector);
                 }
@@ -739,12 +768,13 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         }
 
         NodeConnector src = edge.getTailNodeConnector();
+        NodeConnector dst = edge.getHeadNodeConnector();
         if (!src.getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
-            pendingMap.remove(src);
+            holdTime.put(dst, 0);
         } else {
-            NodeConnector dst = edge.getHeadNodeConnector();
             agingMap.put(dst, 0);
         }
+        elapsedTime.remove(src);
 
         // notify
         updateEdge(edge, UpdateType.ADDED, props);
@@ -812,18 +842,18 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
      * Remove OpenFlow edge
      */
     private void removeEdge(NodeConnector nodeConnector, boolean stillEnabled) {
-        pendingMap.remove(nodeConnector);
+        holdTime.remove(nodeConnector);
         readyListLo.remove(nodeConnector);
         readyListHi.remove(nodeConnector);
 
         if (stillEnabled) {
             // keep discovering
-            if (!waitingList.contains(nodeConnector)) {
-                waitingList.add(nodeConnector);
+            if (!stagingList.contains(nodeConnector)) {
+                stagingList.add(nodeConnector);
             }
         } else {
             // stop it
-            waitingList.remove(nodeConnector);
+            stagingList.remove(nodeConnector);
         }
 
         Edge edge = null;
@@ -873,8 +903,8 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     private void moveToReadyListHi(NodeConnector nodeConnector) {
         if (readyListLo.contains(nodeConnector)) {
             readyListLo.remove(nodeConnector);
-        } else if (waitingList.contains(nodeConnector)) {
-            waitingList.remove(nodeConnector);
+        } else if (stagingList.contains(nodeConnector)) {
+            stagingList.remove(nodeConnector);
         }
         readyListHi.add(nodeConnector);
     }
@@ -888,18 +918,15 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         return discoveryConsistencyCheckMultiple * discoveryBatchRestartTicks;
     }
 
-    private int getDiscoveryFinalTimeoutInterval() {
-        return (discoveryRetry + 1) * discoveryTimeoutTicks;
-    }
-
     @Override
     public String getHelp() {
         StringBuffer help = new StringBuffer();
         help.append("---Topology Discovery---\n");
         help.append("\t prlh                            - Print readyListHi entries\n");
         help.append("\t prll                            - Print readyListLo entries\n");
-        help.append("\t pwl                             - Print waitingList entries\n");
-        help.append("\t ppl                             - Print pendingList entries\n");
+        help.append("\t psl                             - Print stagingList entries\n");
+        help.append("\t pht                             - Print hold time\n");
+        help.append("\t pet                             - Print elapsed time\n");
         help.append("\t ptick                           - Print tick time in msec\n");
         help.append("\t pcc                             - Print CC info\n");
         help.append("\t psize                           - Print sizes of all the lists\n");
@@ -910,8 +937,6 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         help.append("\t sports [ports]                  - Set/show max ports per batch\n");
         help.append("\t spause [ticks]                  - Set/show pause period\n");
         help.append("\t sdi [ticks]                     - Set/show discovery interval in ticks\n");
-        help.append("\t stm [ticks]                     - Set/show per timeout ticks\n");
-        help.append("\t sretry [count]                  - Set/show num of retries\n");
         help.append("\t addsw <swid>                    - Add a switch\n");
         help.append("\t remsw <swid>                    - Remove a switch\n");
         help.append("\t page                            - Print aging info\n");
@@ -927,42 +952,69 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         return help.toString();
     }
 
+    private List<NodeConnector> sortList(Collection<NodeConnector> ncs) {
+        List<String> ncStrArray = new ArrayList<String>();
+        for (NodeConnector nc : ncs) {
+            ncStrArray.add(nc.toString());
+        }
+        Collections.sort(ncStrArray);
+
+        List<NodeConnector> sortedNodeConnectors = new ArrayList<NodeConnector>();
+        for (String ncStr : ncStrArray) {
+            sortedNodeConnectors.add(NodeConnector.fromString(ncStr));
+        }
+
+        return sortedNodeConnectors;
+    }
+
     public void _prlh(CommandInterpreter ci) {
-        ci.println("ReadyListHi\n");
-        for (NodeConnector nodeConnector : readyListHi) {
+        ci.println("readyListHi\n");
+        for (NodeConnector nodeConnector : sortList(readyListHi)) {
             if (nodeConnector == null) {
                 continue;
             }
             ci.println(nodeConnector);
         }
+        ci.println("Total number of Node Connectors: " + readyListHi.size());
     }
 
     public void _prll(CommandInterpreter ci) {
-        ci.println("ReadyListLo\n");
-        for (NodeConnector nodeConnector : readyListLo) {
+        ci.println("readyListLo\n");
+        for (NodeConnector nodeConnector : sortList(readyListLo)) {
             if (nodeConnector == null) {
                 continue;
             }
             ci.println(nodeConnector);
         }
+        ci.println("Total number of Node Connectors: " + readyListLo.size());
     }
 
-    public void _pwl(CommandInterpreter ci) {
-        ci.println("WaitingList\n");
-        for (NodeConnector nodeConnector : waitingList) {
+    public void _psl(CommandInterpreter ci) {
+        ci.println("stagingList\n");
+        for (NodeConnector nodeConnector : sortList(stagingList)) {
             if (nodeConnector == null) {
                 continue;
             }
             ci.println(nodeConnector);
         }
+        ci.println("Total number of Node Connectors: " + stagingList.size());
+    }
+
+    public void _pht(CommandInterpreter ci) {
+        ci.println("          NodeConnector            Last rx LLDP (sec)");
+        for (ConcurrentMap.Entry<NodeConnector, Integer> entry: holdTime.entrySet()) {
+            ci.println(entry.getKey() + "\t\t" + entry.getValue() * (discoveryTimerTick / 1000));
+        }
+        ci.println("\nSize: " + holdTime.size() + "\tTimeout: " + discoveryTimeoutTicks * (discoveryTimerTick / 1000)
+                + " sec");
     }
 
-    public void _ppl(CommandInterpreter ci) {
-        ci.println("pendingMap\n");
-        ci.println("          NodeConnector            Last rx LLDP (s)");
-        for (ConcurrentMap.Entry<NodeConnector, Integer> entry: pendingMap.entrySet()) {
-            ci.println(entry.getKey() + "\t\t" + entry.getValue());
+    public void _pet(CommandInterpreter ci) {
+        ci.println("          NodeConnector            Elapsed Time (sec)");
+        for (ConcurrentMap.Entry<NodeConnector, Integer> entry: elapsedTime.entrySet()) {
+            ci.println(entry.getKey() + "\t\t" + entry.getValue() * (discoveryTimerTick / 1000));
         }
+        ci.println("\nSize: " + elapsedTime.size() + "\tThreshold: " + DiscoveryPeriod.THRESHOLD.getTime() + " sec");
     }
 
     public void _ptick(CommandInterpreter ci) {
@@ -982,16 +1034,14 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     }
 
     public void _ptm(CommandInterpreter ci) {
-        ci.println("Final timeout ticks " + getDiscoveryFinalTimeoutInterval());
-        ci.println("Per timeout ticks " + discoveryTimeoutTicks);
-        ci.println("Number of retries after initial timeout " + discoveryRetry);
+        ci.println("Timeout " + discoveryTimeoutTicks + " ticks, " + discoveryTimerTick / 1000 + " sec per tick.");
     }
 
     public void _psize(CommandInterpreter ci) {
         ci.println("readyListLo size " + readyListLo.size() + "\n" + "readyListHi size " + readyListHi.size() + "\n"
-                + "waitingList size " + waitingList.size() + "\n" + "pendingMap size " + pendingMap.size() + "\n"
+                + "stagingList size " + stagingList.size() + "\n" + "holdTime size " + holdTime.size() + "\n"
                 + "edgeMap size " + edgeMap.size() + "\n" + "prodMap size " + prodMap.size() + "\n" + "agingMap size "
-                + agingMap.size());
+                + agingMap.size() + "\n" + "elapsedTime size " + elapsedTime.size());
     }
 
     public void _page(CommandInterpreter ci) {
@@ -1136,14 +1186,15 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     public void _spause(CommandInterpreter ci) {
         String val = ci.nextArgument();
         String out = "Please enter pause period less than " + discoveryBatchRestartTicks + ". Current pause period is "
-                + discoveryBatchPausePeriod + " pause tick is " + discoveryBatchPauseTicks + ".";
+                + discoveryBatchPausePeriod + " ticks, pause at " + discoveryBatchPauseTicks + " ticks, "
+                + discoveryTimerTick / 1000 + " sec per tick.";
 
         if (val != null) {
             try {
                 int pause = Integer.parseInt(val);
                 if (pause < discoveryBatchRestartTicks) {
                     discoveryBatchPausePeriod = pause;
-                    discoveryBatchPauseTicks = discoveryBatchRestartTicks - discoveryBatchPausePeriod;
+                    discoveryBatchPauseTicks = getDiscoveryPauseInterval();
                     return;
                 }
             } catch (Exception e) {
@@ -1155,17 +1206,17 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
 
     public void _sdi(CommandInterpreter ci) {
         String val = ci.nextArgument();
-        String out = "Please enter discovery interval greater than " + discoveryBatchPausePeriod
-                + ". Current value is " + discoveryBatchRestartTicks + ".";
+        String out = "Please enter discovery interval in ticks. Current value is " + discoveryBatchRestartTicks + " ticks, "
+                + discoveryTimerTick / 1000 + " sec per tick.";
 
         if (val != null) {
             try {
-                int restart = Integer.parseInt(val);
-                if (restart > discoveryBatchPausePeriod) {
-                    discoveryBatchRestartTicks = restart;
-                    discoveryBatchPauseTicks = discoveryBatchRestartTicks - discoveryBatchPausePeriod;
-                    return;
-                }
+                int ticks = Integer.parseInt(val);
+                DiscoveryPeriod.INTERVAL.setTick(ticks);
+                discoveryBatchRestartTicks = getDiscoveryInterval();
+                discoveryBatchPauseTicks = getDiscoveryPauseInterval();
+                discoveryTimeoutTicks = getDiscoveryTimeout();
+                return;
             } catch (Exception e) {
             }
         }
@@ -1186,38 +1237,6 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         return;
     }
 
-    public void _sretry(CommandInterpreter ci) {
-        String val = ci.nextArgument();
-        if (val == null) {
-            ci.println("Please enter number of retries. Current value is " + discoveryRetry);
-            return;
-        }
-        try {
-            discoveryRetry = Integer.parseInt(val);
-        } catch (Exception e) {
-            ci.println("Please enter a valid number");
-        }
-        return;
-    }
-
-    public void _stm(CommandInterpreter ci) {
-        String val = ci.nextArgument();
-        String out = "Please enter timeout tick value less than " + discoveryBatchRestartTicks + ". Current value is "
-                + discoveryTimeoutTicks;
-        if (val != null) {
-            try {
-                int timeout = Integer.parseInt(val);
-                if (timeout < discoveryBatchRestartTicks) {
-                    discoveryTimeoutTicks = timeout;
-                    return;
-                }
-            } catch (Exception e) {
-            }
-        }
-
-        ci.println(out);
-    }
-
     public void _addsw(CommandInterpreter ci) {
         String val = ci.nextArgument();
         Long sid;
@@ -1403,13 +1422,22 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
 
         readyListHi = new CopyOnWriteArrayList<NodeConnector>();
         readyListLo = new CopyOnWriteArrayList<NodeConnector>();
-        waitingList = new CopyOnWriteArrayList<NodeConnector>();
-        pendingMap = new ConcurrentHashMap<NodeConnector, Integer>();
+        stagingList = new CopyOnWriteArrayList<NodeConnector>();
+        holdTime = new ConcurrentHashMap<NodeConnector, Integer>();
+        elapsedTime = new ConcurrentHashMap<NodeConnector, Integer>();
         edgeMap = new ConcurrentHashMap<NodeConnector, Edge>();
         agingMap = new ConcurrentHashMap<NodeConnector, Integer>();
         prodMap = new ConcurrentHashMap<NodeConnector, Edge>();
         discoverySnoopingDisableList = new CopyOnWriteArrayList<NodeConnector>();
 
+        discoveryBatchRestartTicks = getDiscoveryInterval();
+        discoveryBatchPauseTicks = getDiscoveryPauseInterval();
+        discoveryTimeoutTicks = getDiscoveryTimeout();
+        discoveryThresholdTicks = getDiscoveryThreshold();
+        discoveryAgeoutTicks = getDiscoveryAgeout();
+        discoveryConsistencyCheckTickCount = discoveryBatchPauseTicks;
+        discoveryBatchMaxPorts = getDiscoveryBatchMaxPorts();
+
         discoveryTimer = new Timer("DiscoveryService");
         discoveryTimerTask = new DiscoveryTimerTask();
 
@@ -1430,8 +1458,8 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
         transmitQ = null;
         readyListHi = null;
         readyListLo = null;
-        waitingList = null;
-        pendingMap = null;
+        stagingList = null;
+        holdTime = null;
         edgeMap = null;
         agingMap = null;
         prodMap = null;
@@ -1534,14 +1562,31 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     }
 
     /**
-     * This method returns the timeout value in waiting for response of a
-     * discovery query.
+     * This method returns the timeout value in receiving subsequent discovery packets on a port.
      *
      * @return The discovery timeout in ticks
      */
     private int getDiscoveryTimeout() {
-        String timeout = System.getProperty("of.discoveryTimeout");
-        return getDiscoveryTicks(DiscoveryPeriod.TIMEOUT, timeout);
+        String val = System.getProperty("of.discoveryTimeoutMultiple");
+        int multiple = 2;
+
+        if (val != null) {
+            try {
+                multiple = Integer.parseInt(val);
+            } catch (Exception e) {
+            }
+        }
+        return getDiscoveryInterval() * multiple + 3;
+    }
+
+    /**
+     * This method returns the user configurable threshold value
+     *
+     * @return The discovery threshold value in ticks
+     */
+    private int getDiscoveryThreshold() {
+        String val = System.getProperty("of.discoveryThreshold");
+        return getDiscoveryTicks(DiscoveryPeriod.THRESHOLD, val);
     }
 
     /**
@@ -1554,22 +1599,34 @@ public class DiscoveryService implements IInventoryShimExternalListener, IDataPa
     }
 
     /**
-     * This method returns the number of retries after the initial discovery
-     * packet is not received within the timeout period. Default is 2 times.
+     * This method returns the pause interval
      *
-     * @return The number of discovery retries
+     * @return The pause interval in ticks
      */
-    private int getDiscoveryRetry() {
-        String retry = System.getProperty("of.discoveryRetry");
-        int rv = 2;
+    private int getDiscoveryPauseInterval() {
+        if (discoveryBatchRestartTicks > discoveryBatchPausePeriod) {
+            return discoveryBatchRestartTicks - discoveryBatchPausePeriod;
+        } else {
+            return discoveryBatchRestartTicks - 1;
+        }
+    }
 
-        if (retry != null) {
+    /**
+     * This method returns the user configurable maximum number of ports handled
+     * in one discovery batch.
+     *
+     * @return The maximum number of ports
+     */
+    private int getDiscoveryBatchMaxPorts() {
+        String val = System.getProperty("of.discoveryBatchMaxPorts");
+        int ports = 1024;
+
+        if (val != null) {
             try {
-                rv = Integer.parseInt(retry);
+                ports = Integer.parseInt(val);
             } catch (Exception e) {
             }
         }
-
-        return rv;
+        return ports;
     }
 }
index 024549de596a7813eb191a18f35cae2c23babfc7..837426eda42576ceb09ebb169e40ce954983df62 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.controller.protocol_plugin.openflow.internal;
 
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.List;
@@ -16,6 +17,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CopyOnWriteArraySet;
 
 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener;
 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimInternalListener;
@@ -27,13 +29,11 @@ import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitchStateLis
 import org.opendaylight.controller.sal.core.Actions;
 import org.opendaylight.controller.sal.core.Buffers;
 import org.opendaylight.controller.sal.core.Capabilities;
-import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.ContainerFlow;
 import org.opendaylight.controller.sal.core.Description;
 import org.opendaylight.controller.sal.core.IContainerListener;
 import org.opendaylight.controller.sal.core.MacAddress;
 import org.opendaylight.controller.sal.core.Node;
-import org.opendaylight.controller.sal.core.Node.NodeIDType;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.core.Tables;
@@ -64,7 +64,10 @@ public class InventoryServiceShim implements IContainerListener,
     private IController controller = null;
     private final ConcurrentMap<String, IInventoryShimInternalListener> inventoryShimInternalListeners = new ConcurrentHashMap<String, IInventoryShimInternalListener>();
     private final List<IInventoryShimExternalListener> inventoryShimExternalListeners = new CopyOnWriteArrayList<IInventoryShimExternalListener>();
-    private final ConcurrentMap<NodeConnector, List<String>> containerMap = new ConcurrentHashMap<NodeConnector, List<String>>();
+    private final ConcurrentMap<NodeConnector, Set<String>> nodeConnectorContainerMap = new ConcurrentHashMap<NodeConnector, Set<String>>();
+    private final ConcurrentMap<Node, Set<String>> nodeContainerMap = new ConcurrentHashMap<Node, Set<String>>();
+    private final ConcurrentMap<NodeConnector, Set<Property>> nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Set<Property>>();
+    private final ConcurrentMap<Node, Set<Property>> nodeProps = new ConcurrentHashMap<Node, Set<Property>>();
 
     void setController(IController s) {
         this.controller = s;
@@ -162,7 +165,8 @@ public class InventoryServiceShim implements IContainerListener,
         this.controller.removeSwitchStateListener(this);
 
         this.inventoryShimInternalListeners.clear();
-        this.containerMap.clear();
+        this.nodeConnectorContainerMap.clear();
+        this.nodeContainerMap.clear();
         this.controller = null;
     }
 
@@ -178,21 +182,24 @@ public class InventoryServiceShim implements IContainerListener,
         Node node = NodeCreator.createOFNode(sw.getId());
         NodeConnector nodeConnector = PortConverter.toNodeConnector(
             m.getDesc().getPortNumber(), node);
+        // get node connector properties
+        Set<Property> props = InventoryServiceHelper.OFPortToProps(m.getDesc());
 
         UpdateType type = null;
         if (m.getReason() == (byte) OFPortReason.OFPPR_ADD.ordinal()) {
             type = UpdateType.ADDED;
+            nodeConnectorProps.put(nodeConnector, props);
         } else if (m.getReason() == (byte) OFPortReason.OFPPR_DELETE.ordinal()) {
             type = UpdateType.REMOVED;
+            nodeConnectorProps.remove(nodeConnector);
         } else if (m.getReason() == (byte) OFPortReason.OFPPR_MODIFY.ordinal()) {
             type = UpdateType.CHANGED;
+            nodeConnectorProps.put(nodeConnector, props);
         }
 
         logger.trace("handlePortStatusMessage {} type {}", nodeConnector, type);
 
         if (type != null) {
-            // get node connector properties
-            Set<Property> props = InventoryServiceHelper.OFPortToProps(m.getDesc());
             notifyInventoryShimListener(nodeConnector, type, props);
         }
     }
@@ -207,6 +214,12 @@ public class InventoryServiceShim implements IContainerListener,
         Map<NodeConnector, Set<Property>> ncProps = InventoryServiceHelper
                 .OFSwitchToProps(sw);
         for (Map.Entry<NodeConnector, Set<Property>> entry : ncProps.entrySet()) {
+            Set<Property> props = new HashSet<Property>();
+            Set<Property> prop = entry.getValue();
+            if (prop != null) {
+                props.addAll(prop);
+            }
+            nodeConnectorProps.put(entry.getKey(), props);
             notifyInventoryShimListener(entry.getKey(), UpdateType.ADDED,
                     entry.getValue());
         }
@@ -242,48 +255,68 @@ public class InventoryServiceShim implements IContainerListener,
     }
 
     @Override
-    public void nodeConnectorUpdated(String containerName, NodeConnector p,
-            UpdateType t) {
-        logger.debug("nodeConnectorUpdated: {} type {} for container {}",
-                new Object[] { p, t, containerName });
-        if (this.containerMap == null) {
-            logger.error("containerMap is NULL");
-            return;
+    public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType t) {
+        logger.debug("nodeConnectorUpdated: {} type {} for container {}", new Object[] { p, t, containerName });
+        Node node = p.getNode();
+        Set<String> ncContainers = this.nodeConnectorContainerMap.get(p);
+        Set<String> nodeContainers = this.nodeContainerMap.get(node);
+        if (ncContainers == null) {
+            ncContainers = new CopyOnWriteArraySet<String>();
         }
-        List<String> containers = this.containerMap.get(p);
-        if (containers == null) {
-            containers = new CopyOnWriteArrayList<String>();
+        if (nodeContainers == null) {
+            nodeContainers = new CopyOnWriteArraySet<String>();
         }
-        boolean updateMap = false;
+        boolean notifyNodeUpdate = false;
+
         switch (t) {
         case ADDED:
-            if (!containers.contains(containerName)) {
-                containers.add(containerName);
-                updateMap = true;
+            if (ncContainers.add(containerName)) {
+                this.nodeConnectorContainerMap.put(p, ncContainers);
+            }
+            if (nodeContainers.add(containerName)) {
+                this.nodeContainerMap.put(node, nodeContainers);
+                notifyNodeUpdate = true;
             }
             break;
         case REMOVED:
-            if (containers.contains(containerName)) {
-                containers.remove(containerName);
-                updateMap = true;
+            if (ncContainers.remove(containerName)) {
+                if (ncContainers.isEmpty()) {
+                    // Do cleanup to reduce memory footprint if no
+                    // elements to be tracked
+                    this.nodeConnectorContainerMap.remove(p);
+                } else {
+                    this.nodeConnectorContainerMap.put(p, ncContainers);
+                }
+            }
+            boolean nodeContainerUpdate = true;
+            for (NodeConnector nc : nodeConnectorContainerMap.keySet()) {
+                if ((nc.getNode().equals(node)) && (nodeConnectorContainerMap.get(nc).contains(containerName))) {
+                    nodeContainerUpdate = false;
+                    break;
+                }
+            }
+            if (nodeContainerUpdate) {
+                nodeContainers.remove(containerName);
+                notifyNodeUpdate = true;
+                if (nodeContainers.isEmpty()) {
+                    this.nodeContainerMap.remove(node);
+                } else {
+                    this.nodeContainerMap.put(node, nodeContainers);
+                }
             }
             break;
         case CHANGED:
             break;
         }
-        if (updateMap) {
-            if (containers.isEmpty()) {
-                // Do cleanup to reduce memory footprint if no
-                // elements to be tracked
-                this.containerMap.remove(p);
-            } else {
-                this.containerMap.put(p, containers);
-            }
-        }
 
+        Set<Property> ncProp = nodeConnectorProps.get(p);
         // notify InventoryService
-        notifyInventoryShimInternalListener(containerName, p, t, null);
-        notifyInventoryShimInternalListener(containerName, p.getNode(), t, null);
+        notifyInventoryShimInternalListener(containerName, p, t, ncProp);
+
+        if (notifyNodeUpdate) {
+            Set<Property> nodeProp = nodeProps.get(node);
+            notifyInventoryShimInternalListener(containerName, node, t, nodeProp);
+        }
     }
 
     private void notifyInventoryShimExternalListener(Node node,
@@ -316,21 +349,13 @@ public class InventoryServiceShim implements IContainerListener,
     /*
      * Notify all internal and external listeners
      */
-    private void notifyInventoryShimListener(NodeConnector nodeConnector,
-            UpdateType type, Set<Property> props) {
-        // Always notify default InventoryService. Store properties in default
-        // one.
-        notifyInventoryShimInternalListener(GlobalConstants.DEFAULT.toString(),
-                nodeConnector, type, props);
-
-        // Now notify other containers
-        List<String> containers = containerMap.get(nodeConnector);
-        if (containers != null) {
-            for (String container : containers) {
-                // no property stored in container components.
-                notifyInventoryShimInternalListener(container, nodeConnector,
-                        type, null);
-            }
+    private void notifyInventoryShimListener(NodeConnector nodeConnector, UpdateType type, Set<Property> props) {
+        // notify other containers
+        Set<String> containers = (nodeConnectorContainerMap.get(nodeConnector) == null) ? new HashSet<String>()
+                : new HashSet<String>(nodeConnectorContainerMap.get(nodeConnector));
+        containers.add(GlobalConstants.DEFAULT.toString());
+        for (String container : containers) {
+            notifyInventoryShimInternalListener(container, nodeConnector, type, props);
         }
 
         // Notify DiscoveryService
@@ -340,34 +365,13 @@ public class InventoryServiceShim implements IContainerListener,
     /*
      * Notify all internal and external listeners
      */
-    private void notifyInventoryShimListener(Node node, UpdateType type,
-            Set<Property> props) {
-        switch (type) {
-        case ADDED:
-            // Notify only the default Inventory Service
-            IInventoryShimInternalListener inventoryShimDefaultListener = inventoryShimInternalListeners
-                    .get(GlobalConstants.DEFAULT.toString());
-            if (inventoryShimDefaultListener != null) {
-                inventoryShimDefaultListener.updateNode(node, type, props);
-            }
-            break;
-        case REMOVED:
-            // Notify all Inventory Service containers
-            for (IInventoryShimInternalListener inventoryShimInternalListener : inventoryShimInternalListeners
-                    .values()) {
-                inventoryShimInternalListener.updateNode(node, type, null);
-            }
-            break;
-        case CHANGED:
-            // Notify only the default Inventory Service
-            inventoryShimDefaultListener = inventoryShimInternalListeners
-                    .get(GlobalConstants.DEFAULT.toString());
-            if (inventoryShimDefaultListener != null) {
-                inventoryShimDefaultListener.updateNode(node, type, props);
-            }
-            break;
-        default:
-            break;
+    private void notifyInventoryShimListener(Node node, UpdateType type, Set<Property> props) {
+        // Now notify other containers
+        Set<String> containers = (nodeContainerMap.get(node) == null) ? new HashSet<String>() : new HashSet<String>(
+                nodeContainerMap.get(node));
+        containers.add(GlobalConstants.DEFAULT.toString());
+        for (String container : containers) {
+            notifyInventoryShimInternalListener(container, node, type, props);
         }
 
         // Notify external listener
@@ -421,21 +425,19 @@ public class InventoryServiceShim implements IContainerListener,
             props.add(b);
         }
 
+        nodeProps.put(node, props);
         // Notify all internal and external listeners
         notifyInventoryShimListener(node, type, props);
     }
 
     private void removeNode(ISwitch sw) {
-        Node node;
-        try {
-            node = new Node(NodeIDType.OPENFLOW, sw.getId());
-        } catch (ConstructionException e) {
-            logger.error("{}", e.getMessage());
+        Node node = NodeCreator.createOFNode(sw.getId());
+        if(node == null) {
             return;
         }
-
+        removeNodeConnectorProps(node);
+        nodeProps.remove(node);
         UpdateType type = UpdateType.REMOVED;
-
         // Notify all internal and external listeners
         notifyInventoryShimListener(node, type, null);
     }
@@ -448,6 +450,18 @@ public class InventoryServiceShim implements IContainerListener,
         }
     }
 
+    private void removeNodeConnectorProps(Node node) {
+        List<NodeConnector> ncList = new ArrayList<NodeConnector>();
+        for (NodeConnector nc : nodeConnectorProps.keySet()) {
+            if (nc.getNode().equals(node)) {
+                ncList.add(nc);
+            }
+        }
+        for (NodeConnector nc : ncList) {
+            nodeConnectorProps.remove(nc);
+        }
+    }
+
     @Override
     public void descriptionStatisticsRefreshed(Long switchId, List<OFStatistics> descriptionStats) {
         Node node = NodeCreator.createOFNode(switchId);
index bcaf3a062a754e4ea5303723a4159a3226c75bdb..ec57cb4a3ca73185fe428bd25ccae4b6e0d7d60f 100644 (file)
@@ -11,7 +11,6 @@ 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;
 
-import java.util.*;
 import java.util.concurrent.Future;
 
 import java.util.ArrayList;
@@ -21,9 +20,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.Future;
 
-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.GeneratedTOBuilderImpl;
@@ -856,11 +853,11 @@ public final class BindingGeneratorImpl implements BindingGenerator {
                     if (genTOBuilder != null) {
                         returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
                     }
-                } else if(typeDef instanceof BitsTypeDefinition) {
+                } else if (typeDef instanceof BitsTypeDefinition) {
                     GeneratedTOBuilder genTOBuilder = addEnclosedTOToTypeBuilder(typeDef, typeBuilder, leafName);
                     if (genTOBuilder != null) {
                         returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
-                    }                    
+                    }
                 } else {
                     returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef);
                 }
@@ -1184,23 +1181,23 @@ public final class BindingGeneratorImpl implements BindingGenerator {
         return genTOBuilder;
     }
 
-    
-    private GeneratedTOBuilder addEnclosedTOToTypeBuilder( TypeDefinition<?> typeDef, GeneratedTypeBuilder typeBuilder, String leafName) { 
+    private GeneratedTOBuilder addEnclosedTOToTypeBuilder(TypeDefinition<?> typeDef, GeneratedTypeBuilder typeBuilder,
+            String leafName) {
         String className = parseToClassName(leafName);
         GeneratedTOBuilder genTOBuilder = null;
         if (typeDef instanceof UnionType) {
             genTOBuilder = ((TypeProviderImpl) typeProvider).addUnionGeneratedTypeDefinition(
                     typeBuilder.getPackageName(), typeDef, className);
         } else if (typeDef instanceof BitsTypeDefinition) {
-            genTOBuilder = ((TypeProviderImpl) typeProvider).bitsTypedefToTransferObject(
-                    typeBuilder.getPackageName(), typeDef, className);
+            genTOBuilder = ((TypeProviderImpl) typeProvider).bitsTypedefToTransferObject(typeBuilder.getPackageName(),
+                    typeDef, className);
         }
         if (genTOBuilder != null) {
             typeBuilder.addEnclosingTransferObject(genTOBuilder);
             return genTOBuilder;
         }
         return null;
-        
+
     }
-    
+
 }
index 4824fa75fd000be4910397bc7bd02f3e3775d6ad..b6d8de62e6d170d6e7e4a44f7cfe6944e2bfed7c 100644 (file)
@@ -27,13 +27,16 @@ import org.opendaylight.controller.yang.model.api.type.*;
 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
+
 import org.opendaylight.controller.yang.model.util.StringType;
+import org.opendaylight.controller.yang.model.util.UnionType;
 
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.TreeMap;
 
 import static org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil.*;
 import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.*;
@@ -361,18 +364,15 @@ public final class TypeProviderImpl implements TypeProvider {
             final String basePackageName = moduleNamespaceToPackageName(module);
 
             final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
+            final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
 
             final Map<String, Type> typeMap = new HashMap<>();
             genTypeDefsContextMap.put(moduleName, typeMap);
 
-            if ((typeDefinitions != null) && (basePackageName != null)) {
-                for (final TypeDefinition<?> typedef : typeDefinitions) {
+            if ((listTypeDefinitions != null) && (basePackageName != null)) {
+                for (final TypeDefinition<?> typedef : listTypeDefinitions) {
                     typedefToGeneratedType(basePackageName, moduleName, typedef);
                 }
-                final List<ExtendedType> extUnions = UnionDependencySort.sort(typeDefinitions);
-                for (final ExtendedType extUnionType : extUnions) {
-                    addUnionGeneratedTypeDefinition(basePackageName, extUnionType, null);
-                }
             }
         }
     }
@@ -382,23 +382,31 @@ public final class TypeProviderImpl implements TypeProvider {
         if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
 
             final String typedefName = typedef.getQName().getLocalName();
-            final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
-            if (!(baseTypeDefinition instanceof LeafrefTypeDefinition)
-                    && !(baseTypeDefinition instanceof IdentityrefTypeDefinition)) {
-                Type returnType;
-                if (baseTypeDefinition instanceof EnumTypeDefinition) {
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDefinition;
+            final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
+            if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
+                    && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
+                Type returnType = null;
+                if (innerTypeDefinition instanceof ExtendedType) {
+                    ExtendedType extendedTypeDef = (ExtendedType) innerTypeDefinition;
+                    returnType = resolveExtendedTypeFromTypeDef(extendedTypeDef, basePackageName, typedefName,
+                            moduleName);
+                } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
+                    final GeneratedTOBuilder genTOBuilder = addUnionGeneratedTypeDefinition(basePackageName, typedef,
+                            typedefName);
+                    returnType = genTOBuilder.toInstance();
+                } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
+                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
                     returnType = resolveEnumFromTypeDefinition(enumTypeDef, typedefName);
 
-                } else if (baseTypeDefinition instanceof BitsTypeDefinition) {
-                    final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) baseTypeDefinition;
-                    GeneratedTOBuilder genTOBuilder = bitsTypedefToTransferObject(basePackageName, bitsTypeDefinition,
-                            typedefName);
+                } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
+                    final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
+                    final GeneratedTOBuilder genTOBuilder = bitsTypedefToTransferObject(basePackageName,
+                            bitsTypeDefinition, typedefName);
                     returnType = genTOBuilder.toInstance();
 
                 } else {
                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
-                            .javaTypeForSchemaDefinitionType(baseTypeDefinition);
+                            .javaTypeForSchemaDefinitionType(innerTypeDefinition);
 
                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
                 }
@@ -428,12 +436,12 @@ public final class TypeProviderImpl implements TypeProvider {
             genTOBuilder.addEqualsIdentity(genPropBuilder);
             genTOBuilder.addHashIdentity(genPropBuilder);
             genTOBuilder.addToStringProperty(genPropBuilder);
-
-            if (typedef instanceof ExtendedType) {
-                final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
-                addStringRegExAsConstant(genTOBuilder, regExps);
+            if (javaType == BaseYangTypes.STRING_TYPE) {
+                if (typedef instanceof ExtendedType) {
+                    final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
+                    addStringRegExAsConstant(genTOBuilder, regExps);
+                }
             }
-
             return genTOBuilder.toInstance();
         }
         return null;
@@ -479,9 +487,10 @@ public final class TypeProviderImpl implements TypeProvider {
                     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);
+                        Type genTransferObject = null;
+                        if (innerGenTOs != null) {
+                            genTransferObject = innerGenTOs.get(typeName);
+                        }
                         if (genTransferObject != null) {
                             updateUnionTypeAsProperty(unionGenTransObject, genTransferObject,
                                     genTransferObject.getName());
@@ -620,4 +629,103 @@ public final class TypeProviderImpl implements TypeProvider {
         }
     }
 
+    private GeneratedTransferObject resolveExtendedTypeFromTypeDef(final ExtendedType extendedType,
+            final String basePackageName, final String typedefName, final String moduleName) {
+
+        if (extendedType == null) {
+            throw new IllegalArgumentException("Extended type cannot be NULL!");
+        }
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("String with base package name cannot be NULL!");
+        }
+        if (typedefName == null) {
+            throw new IllegalArgumentException("String with type definition name cannot be NULL!");
+        }
+
+        final String typeDefName = parseToClassName(typedefName);
+        final String lowTypeDef = extendedType.getQName().getLocalName();
+        final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName);
+
+        final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
+        if (typeMap != null) {
+            Type type = typeMap.get(lowTypeDef);
+            if (type instanceof GeneratedTransferObject) {
+                genTOBuilder.setExtendsType((GeneratedTransferObject) type);
+            }
+        }
+
+        return genTOBuilder.toInstance();
+    }
+
+    /**
+     * The method find out for each type definition how many immersion (depth)
+     * is necessary to get to the base type. Every type definition is inserted
+     * to the map which key is depth and value is list of type definitions with
+     * equal depth. In next step are lists from this map concatenated to one
+     * list in ascending order according to their depth. All type definitions
+     * are in the list behind all type definitions on which depends.
+     * 
+     * @param unsortedTypeDefinitions
+     *            represents list of type definitions
+     * @return list of type definitions sorted according their each other
+     *         dependencies (type definitions which are depend on other type
+     *         definitions are in list behind them).
+     */
+    private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
+            final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
+        List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
+
+        Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
+        for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
+            final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
+            List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
+            if (typeDefinitionsConcreteDepth == null) {
+                typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
+                typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
+            }
+            typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
+        }
+
+        Set<Integer> depths = typeDefinitionsDepths.keySet(); // keys are in
+                                                              // ascending order
+        for (Integer depth : depths) {
+            sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
+        }
+
+        return sortedTypeDefinition;
+    }
+
+    /**
+     * The method return how many immersion is necessary to get from type
+     * definition to base type.
+     * 
+     * @param typeDefinition
+     *            is type definition for which is depth looked for.
+     * @return how many immersion is necessary to get from type definition to
+     *         base type
+     */
+    private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type definition can't be null");
+        }
+        int depth = 1;
+        TypeDefinition<?> baseType = typeDefinition.getBaseType();
+
+        if (baseType instanceof ExtendedType) {
+            depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
+        } else if (baseType instanceof UnionType) {
+            List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
+            int maxChildDepth = 0;
+            int childDepth = 1;
+            for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
+                childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
+                if (childDepth > maxChildDepth) {
+                    maxChildDepth = childDepth;
+                }
+            }
+            return maxChildDepth;
+        }
+        return depth;
+    }
+
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/ExtendedTypedefTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/ExtendedTypedefTest.java
new file mode 100644 (file)
index 0000000..bbbf469
--- /dev/null
@@ -0,0 +1,137 @@
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertFalse;
+
+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.generator.impl.BindingGeneratorImpl;
+import org.opendaylight.controller.sal.binding.model.api.Constant;
+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.ParameterizedType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.yang.types.BaseYangTypes;
+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;
+
+public class ExtendedTypedefTest {
+
+    private final static List<File> testModels = new ArrayList<File>();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File listModelFile = new File(ExtendedTypedefTest.class.getResource("/typedef_of_typedef.yang").getPath());
+        testModels.add(listModelFile);
+    }
+
+    @Test    
+    public void constantGenerationTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(testModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull(context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        GeneratedTransferObject simpleTypedef4 = null;
+        GeneratedTransferObject extendedTypedefUnion = null;
+        GeneratedTransferObject unionTypedef = null;
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedTransferObject) {
+                if (type.getName().equals("SimpleTypedef4")) {
+                    simpleTypedef4 = (GeneratedTransferObject) type;
+                } else if (type.getName().equals("ExtendedTypedefUnion")) {
+                    extendedTypedefUnion = (GeneratedTransferObject) type;
+                } else if (type.getName().equals("UnionTypedef")) {
+                    unionTypedef = (GeneratedTransferObject) type;
+                }
+            }
+        }
+
+        // simple-typedef4
+        assertNotNull("SimpleTypedef4 not found", simpleTypedef4);
+        assertNotNull("ExtendedTypedefUnion not found", extendedTypedefUnion);
+        assertNotNull("UnionTypedef", unionTypedef);
+
+        List<GeneratedProperty> properties = simpleTypedef4.getProperties();
+        assertTrue("SimpleTypedef4 shouldn't have properties.", properties.isEmpty());
+
+        GeneratedTransferObject extendTO = simpleTypedef4.getExtends();
+        assertNotNull("SimpleTypedef4 should have extend.", extendTO);
+        assertEquals("Incorrect extension for SimpleTypedef4.", "SimpleTypedef3", extendTO.getName());
+        properties = extendTO.getProperties();
+        assertTrue("SimpleTypedef3 shouldn't have properties.", properties.isEmpty());
+
+        extendTO = extendTO.getExtends();
+        assertNotNull("SimpleTypedef3 should have extend.", extendTO);
+        assertEquals("Incorrect extension for SimpleTypedef3.", "SimpleTypedef2", extendTO.getName());
+        properties = extendTO.getProperties();
+        assertTrue("SimpleTypedef2 shouldn't have properties.", properties.isEmpty());
+
+        extendTO = extendTO.getExtends();
+        assertNotNull("SimpleTypedef2 should have extend.", extendTO);
+        assertEquals("SimpleTypedef2 should be extended with SimpleTypedef1.", "SimpleTypedef1", extendTO.getName());
+        properties = extendTO.getProperties();
+        assertEquals("Incorrect number of properties in class SimpleTypedef1.", 1, properties.size());
+
+        assertEquals("Incorrect property's name", "simpleTypedef1", properties.get(0).getName());
+        assertEquals("Property's incorrect type", BaseYangTypes.UINT8_TYPE, properties.get(0).getReturnType());
+
+        extendTO = extendTO.getExtends();
+        assertNull("SimpleTypedef1 shouldn't have extend.", extendTO);
+
+        // extended-typedef-union
+        assertNotNull("ExtendedTypedefUnion object not found", extendedTypedefUnion);
+        properties = extendedTypedefUnion.getProperties();
+        assertTrue("ExtendedTypedefUnion shouldn't have any property", properties.isEmpty());
+
+        extendTO = extendedTypedefUnion.getExtends();
+        assertEquals("Incorrect extension fo ExtendedTypedefUnion.", "UnionTypedef", extendTO.getName());
+        assertNull("UnionTypedef shouldn't be extended", extendTO.getExtends());
+        assertEquals("Incorrect number of properties for UnionTypedef.", 4, extendTO.getProperties().size());
+
+        GeneratedProperty simpleTypedef4Property = null;
+        GeneratedProperty simpleTypedef1Property = null;
+        GeneratedProperty byteTypeProperty = null;
+        GeneratedProperty typedefEnumFruitProperty = null;
+        for (GeneratedProperty genProperty : extendTO.getProperties()) {
+            if (genProperty.getName().equals("simpleTypedef1")) {
+                simpleTypedef1Property = genProperty;
+            } else if (genProperty.getName().equals("simpleTypedef4")) {
+                simpleTypedef4Property = genProperty;
+            } else if (genProperty.getName().equals("byteType")) {
+                byteTypeProperty = genProperty;
+            } else if (genProperty.getName().equals("typedefEnumFruit")) {
+                typedefEnumFruitProperty = genProperty;
+            }
+        }
+
+        assertNotNull("simpleTypedef4 property not found in UnionTypedef", simpleTypedef4Property);
+        assertNotNull("simpleTypedef1 property not found in UnionTypedef", simpleTypedef1Property);
+        assertNotNull("byteType property not found in UnionTypedef", byteTypeProperty);
+        assertNotNull("typedefEnumFruit property not found in UnionTypedef", typedefEnumFruitProperty);
+
+        assertEquals("Incorrect type for property simpleTypedef4.", "SimpleTypedef4", simpleTypedef4Property
+                .getReturnType().getName());
+        assertEquals("Incorrect type for property simpleTypedef1.", "SimpleTypedef1", simpleTypedef1Property
+                .getReturnType().getName());
+        assertEquals("Incorrect type for property byteType.", "ByteType", byteTypeProperty
+                .getReturnType().getName());
+        assertEquals("Incorrect type for property typedefEnumFruit.", "TypedefEnumFruit", typedefEnumFruitProperty
+                .getReturnType().getName());
+    }
+
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/typedef_of_typedef.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/typedef_of_typedef.yang
new file mode 100644 (file)
index 0000000..fc0bab9
--- /dev/null
@@ -0,0 +1,79 @@
+module typedef_typedef {
+    
+    namespace "urn:typedef:typedef";
+    prefix "sbd";
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    revision 2013-07-09 {
+        
+    }
+
+   typedef byte-type {
+        type bits {
+            bit first-bit {
+                position 10;
+            }
+            bit second-bit {
+                position 20;
+            }
+         }
+    }    
+    
+    
+  typedef typedef-enum-fruit {
+    type enumeration {
+      enum "apple" {
+        value 1;
+        description "gold";
+      }
+      enum "pear" {
+        value 2;
+      }
+    }
+  }    
+    
+    typedef simple-typedef1 {
+        type uint8;
+    }
+    
+    typedef simple-typedef2 {
+        type simple-typedef1;
+    }
+    
+    typedef simple-typedef3 {
+        type simple-typedef2;
+    }
+    
+    typedef simple-typedef4 {
+        type simple-typedef3;
+    }
+    
+    typedef simple-typedef1-1 {
+        type uint16;
+    }
+
+    
+    typedef union-typedef {
+        type union {
+            type simple-typedef1;
+            type simple-typedef4;
+            type byte-type;
+            type typedef-enum-fruit;
+        }
+    }
+    
+    typedef extended-typedef-union {
+        type union-typedef;
+    }
+    
+    
+    typedef extended-typedef-simple {
+        type simple-typedef1;
+    }
+    
+    typedef extended-typedef-enum {
+        type typedef-enum-fruit;
+    }
+}
\ No newline at end of file
index 717988af3efef6afaba36b5ef34bad37218b75ce..31b94a65cad703d8b78ca79c8fbaf94f62ea7f70 100644 (file)
@@ -67,11 +67,14 @@ public final class ClassCodeGenerator implements CodeGenerator {
             }
 
             writer.write(NL);
+            final boolean oneConstructor;
             if (genTO.isUnionType()) {
-                writer.write(GeneratorUtil.createConstructors(genTO, indent + TAB, imports, genTO.isAbstract()));
+                oneConstructor = false;
             } else {
-                writer.write(GeneratorUtil.createConstructor(genTO, indent + TAB, imports, genTO.isAbstract()) + NL);
+                oneConstructor = true;
             }
+            writer.write(GeneratorUtil.createConstructor(genTO, indent + TAB, imports, genTO.isAbstract(),
+                    oneConstructor));
             writer.write(NL);
 
             for (GeneratedProperty field : fields) {
index dfae4a2ceaad57c3de7555e7867913416aa78535..0e2da819371cf7b962ba0eba39fa980e1e66bdbd 100644 (file)
@@ -17,9 +17,9 @@ import java.util.Map;
 
 import org.opendaylight.controller.binding.generator.util.TypeConstants;
 import org.opendaylight.controller.sal.binding.model.api.*;
+import org.opendaylight.controller.binding.generator.util.Types;
 import org.opendaylight.controller.sal.binding.model.api.Enumeration.Pair;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Parameter;
-import org.opendaylight.controller.binding.generator.util.Types;
 
 public final class GeneratorUtil {
 
@@ -232,90 +232,244 @@ public final class GeneratorUtil {
         return builder.toString();
     }
 
-    public static String createConstructor(GeneratedTransferObject genTransferObject, final String indent,
-            final Map<String, String> availableImports, boolean isIdentity) {
-        StringBuilder builder = new StringBuilder();
+    public static String createConstructor(final GeneratedTransferObject genTransferObject, final String indent,
+            final Map<String, String> availableImports, final boolean isIdentity, final boolean oneConstructor) {
+        if (genTransferObject == null) {
+            throw new IllegalArgumentException("Generated transfer object can't be null");
+        }
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
+        }
+        GeneratedTransferObject genTOTopParent = getTopParrentTransportObject(genTransferObject);
+        final List<GeneratedProperty> ctorProperties = resolveReadOnlyPropertiesFromTO(genTransferObject
+                .getProperties());
+        final List<GeneratedProperty> ctorPropertiesAllParents = getPropertiesOfAllParents(genTransferObject
+                .getExtends());
 
         final String currentPkg = genTransferObject.getPackageName();
-        final List<GeneratedProperty> properties = genTransferObject.getProperties();
-        final List<GeneratedProperty> ctorParams = new ArrayList<GeneratedProperty>();
-        if (properties != null) {
-            for (final GeneratedProperty property : properties) {
-                if (property.isReadOnly()) {
-                    ctorParams.add(property);
-                }
+        final String className = genTransferObject.getName();
+
+        String constructorPart = "";
+        if (oneConstructor) {
+            if (genTOTopParent != genTransferObject && genTOTopParent.isUnionType()) {
+                constructorPart = createConstructorForEveryParentProperty(indent, isIdentity, ctorProperties,
+                        ctorPropertiesAllParents, availableImports, currentPkg, className);
+
+            } else {
+                constructorPart = createOneConstructor(indent, isIdentity, ctorProperties, ctorPropertiesAllParents,
+                        availableImports, currentPkg, className);
             }
+
+        } else { // union won't be extended
+            constructorPart = createConstructorForEveryProperty(indent, isIdentity, ctorProperties,
+                    ctorPropertiesAllParents, availableImports, currentPkg, className);
         }
 
-        builder.append(createConstructorDeclarationToLeftParenthesis(genTransferObject, indent, isIdentity));
+        return constructorPart;
+    }
 
-        final String parameterSeparator = COMMA + GAP;
-        for (final GeneratedProperty ctorParam : ctorParams) {
-            builder.append(createMethodParamDeclaration(ctorParam, availableImports, currentPkg));
-            builder.append(parameterSeparator);
+    private static String createOneConstructor(final String indent, boolean isIdentity,
+            final List<GeneratedProperty> properties, final List<GeneratedProperty> propertiesAllParents,
+            final Map<String, String> availableImports, final String currentPkg, final String className) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
         }
-        if (!ctorParams.isEmpty()) {
-            builder = builder.delete(builder.length() - parameterSeparator.length(), builder.length());
+        if (properties == null) {
+            throw new IllegalArgumentException("List of generated properties can't be null");
         }
-        builder.append(createConstructorDeclarationFromRightParenthesis());
-        builder.append(createConstructorSuperCalling(indent));
-
-        for (final GeneratedProperty ctorParam : ctorParams) {
-            builder.append(createClassAttributeInitialization(indent, ctorParam));
+        if (propertiesAllParents == null) {
+            throw new IllegalArgumentException(
+                    "List of generated properties of all parent transport objects can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
         }
+        if (currentPkg == null) {
+            throw new IllegalArgumentException("String with current package can't be null");
+        }
+        if (className == null) {
+            throw new IllegalArgumentException("String with class name can't be null");
+        }
+
+        final StringBuilder builder = new StringBuilder();
 
+        List<GeneratedProperty> propertiesAll = new ArrayList<GeneratedProperty>(properties);
+        propertiesAll.addAll(propertiesAllParents);
+
+        builder.append(createConstructorDeclarationToLeftParenthesis(className, indent, isIdentity));
+        builder.append(createMethodPropertiesDeclaration(propertiesAll, availableImports, currentPkg, COMMA + GAP));
+        builder.append(createConstructorDeclarationFromRightParenthesis());
+        builder.append(createConstructorSuper(propertiesAllParents, indent));
+        builder.append(createClassPropertiesInitialization(propertiesAll, indent));
         builder.append(createConstructorClosingPart(indent));
         return builder.toString();
     }
 
-    public static String createConstructors(GeneratedTransferObject genTransferObject, final String indent,
-            final Map<String, String> availableImports, boolean isIdentity) {
+    private static String createConstructorForEveryParentProperty(final String indent, final boolean isIdentity,
+            final List<GeneratedProperty> properties, final List<GeneratedProperty> propertiesAllParents,
+            final Map<String, String> availableImports, final String currentPkg, final String className) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (properties == null) {
+            throw new IllegalArgumentException("List of generated properties can't be null");
+        }
+        if (propertiesAllParents == null) {
+            throw new IllegalArgumentException(
+                    "List of generated properties of all parent transport objects can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
+        }
+        if (currentPkg == null) {
+            throw new IllegalArgumentException("String with current package can't be null");
+        }
+        if (className == null) {
+            throw new IllegalArgumentException("String with class name can't be null");
+        }
         final StringBuilder builder = new StringBuilder();
+        GeneratedProperty parentProperty;
+        Iterator<GeneratedProperty> parentPropertyIterator = propertiesAllParents.iterator();
 
-        final String currentPkg = genTransferObject.getPackageName();
-        final List<GeneratedProperty> properties = genTransferObject.getProperties();
-        final List<GeneratedProperty> ctorParams = new ArrayList<GeneratedProperty>();
-        if (properties != null) {
-            for (final GeneratedProperty property : properties) {
-                if (property.isReadOnly()) {
-                    ctorParams.add(property);
-                }
+        do {
+            parentProperty = null;
+            if (parentPropertyIterator.hasNext()) {
+                parentProperty = parentPropertyIterator.next();
+            }
+
+            List<GeneratedProperty> propertiesAndParentProperties = new ArrayList<GeneratedProperty>();
+            if (parentProperty != null) {
+                propertiesAndParentProperties.add(parentProperty);
             }
+            propertiesAndParentProperties.addAll(properties);
+
+            builder.append(createConstructorDeclarationToLeftParenthesis(className, indent, isIdentity));
+            builder.append(createMethodPropertiesDeclaration(propertiesAndParentProperties, availableImports,
+                    currentPkg, COMMA + GAP));
+            builder.append(createConstructorDeclarationFromRightParenthesis());
+            builder.append(createConstructorSuper(parentProperty, indent));
+            builder.append(createClassPropertiesInitialization(properties, indent));
+            builder.append(createConstructorClosingPart(indent));
+        } while (parentPropertyIterator.hasNext());
+
+        return builder.toString();
+    }
+
+    private static String createConstructorForEveryProperty(final String indent, final boolean isIdentity,
+            final List<GeneratedProperty> properties, final List<GeneratedProperty> propertiesAllParents,
+            final Map<String, String> availableImports, final String currentPkg, final String className) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (properties == null) {
+            throw new IllegalArgumentException("List of generated properties can't be null");
+        }
+        if (propertiesAllParents == null) {
+            throw new IllegalArgumentException(
+                    "List of generated properties of all parent transport objects can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
+        }
+        if (currentPkg == null) {
+            throw new IllegalArgumentException("String with current package can't be null");
+        }
+        if (className == null) {
+            throw new IllegalArgumentException("String with class name can't be null");
         }
 
-        GeneratedProperty ctorParam;
-        Iterator<GeneratedProperty> iteratorCtorParams = ctorParams.iterator();
+        final StringBuilder builder = new StringBuilder();
+
+        GeneratedProperty property;
+        Iterator<GeneratedProperty> propertyIterator = properties.iterator();
 
         do {
-            ctorParam = null;
-            if (iteratorCtorParams.hasNext()) {
-                ctorParam = iteratorCtorParams.next();
+            property = null;
+            if (propertyIterator.hasNext()) {
+                property = propertyIterator.next();
             }
-            builder.append(createConstructorDeclarationToLeftParenthesis(genTransferObject, indent, isIdentity));
 
-            if (ctorParam != null) {
-                builder.append(createMethodParamDeclaration(ctorParam, availableImports, currentPkg));
+            List<GeneratedProperty> propertyAndTopParentProperties = new ArrayList<GeneratedProperty>();
+            if (property != null) {
+                propertyAndTopParentProperties.add(property);
             }
+            propertyAndTopParentProperties.addAll(propertiesAllParents);
+
+            builder.append(createConstructorDeclarationToLeftParenthesis(className, indent, isIdentity));
+            builder.append(createMethodPropertiesDeclaration(propertyAndTopParentProperties, availableImports,
+                    currentPkg, COMMA + GAP));
             builder.append(createConstructorDeclarationFromRightParenthesis());
-            builder.append(createConstructorSuperCalling(indent));
+            builder.append(createConstructorSuper(propertiesAllParents, indent));
+            builder.append(createClassPropertyInitialization(property, indent));
+            builder.append(createConstructorClosingPart(indent));
+        } while (propertyIterator.hasNext());
 
-            if (ctorParam != null) {
-                builder.append(createClassAttributeInitialization(indent, ctorParam));
+        return builder.toString();
+    }
+
+    /**
+     * The method selects from input list of properties only those which have
+     * read only attribute set to true.
+     * 
+     * @param properties
+     *            contains list of properties of generated transfer object
+     * @return subset of <code>properties</code> which have read only attribute
+     *         set to true
+     */
+    private static List<GeneratedProperty> resolveReadOnlyPropertiesFromTO(List<GeneratedProperty> properties) {
+        List<GeneratedProperty> readOnlyProperties = new ArrayList<GeneratedProperty>();
+        if (properties != null) {
+            for (final GeneratedProperty property : properties) {
+                if (property.isReadOnly()) {
+                    readOnlyProperties.add(property);
+                }
             }
+        }
+        return readOnlyProperties;
+    }
 
-            builder.append(createConstructorClosingPart(indent));
-        } while (iteratorCtorParams.hasNext());
+    private static String createMethodPropertiesDeclaration(final List<GeneratedProperty> parameters,
+            final Map<String, String> availableImports, final String currentPkg, final String parameterSeparator) {
+        StringBuilder builder = new StringBuilder();
+        if (parameters == null) {
+            throw new IllegalArgumentException("List of generated properties can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
+        }
+        if (currentPkg == null) {
+            throw new IllegalArgumentException("String with current package can't be null");
+        }
+        if (parameterSeparator == null) {
+            throw new IllegalArgumentException("String with separator of parameters can't be null");
+        }
 
+        for (final GeneratedProperty parameter : parameters) {
+            builder.append(createMethodPropertyDeclaration(parameter, availableImports, currentPkg));
+            builder.append(parameterSeparator);
+        }
+        if (!parameters.isEmpty()) {
+            builder = builder.delete(builder.length() - parameterSeparator.length(), builder.length());
+        }
         return builder.toString();
     }
 
-    private static String createConstructorDeclarationToLeftParenthesis(GeneratedTransferObject genTransferObject,
-            final String indent, boolean isIdentity) {
+    private static String createConstructorDeclarationToLeftParenthesis(final String className, final String indent,
+            final boolean isIdentity) {
+        if (className == null) {
+            throw new IllegalArgumentException("String with class name can't be null");
+        }
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
         final StringBuilder builder = new StringBuilder();
         builder.append(indent);
         builder.append(isIdentity ? PROTECTED : PUBLIC);
         builder.append(GAP);
-        builder.append(genTransferObject.getName());
+        builder.append(className);
         builder.append(LB);
         return builder.toString();
     }
@@ -326,13 +480,48 @@ public final class GeneratorUtil {
         return builder.toString();
     }
 
-    private static String createConstructorSuperCalling(String indent) {
-        final StringBuilder builder = new StringBuilder();
-        builder.append(indent + TAB + "super();" + NL);
+    private static String createConstructorSuper(final List<GeneratedProperty> propertiesAllParents, final String indent) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (propertiesAllParents == null) {
+            throw new IllegalArgumentException("List of all parent's properties can't be null");
+        }
+        StringBuilder builder = new StringBuilder();
+        builder.append(indent + TAB + "super(");
+        String propertySeparator = COMMA + GAP;
+        for (GeneratedProperty superProperty : propertiesAllParents) {
+            builder.append(superProperty.getName());
+            builder.append(propertySeparator);
+        }
+        if (!propertiesAllParents.isEmpty()) {
+            builder = builder.delete(builder.length() - propertySeparator.length(), builder.length());
+        }
+
+        builder.append(");" + NL);
         return builder.toString();
     }
 
-    private static String createConstructorClosingPart(String indent) {
+    private static String createConstructorSuper(final GeneratedProperty parentProperty, final String indent) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (parentProperty == null) {
+            throw new IllegalArgumentException("Parent property can't be null");
+        }
+        StringBuilder builder = new StringBuilder();
+        if (parentProperty != null) {
+            builder.append(indent + TAB + "super(");
+            builder.append(parentProperty.getName());
+            builder.append(");" + NL);
+        }
+        return builder.toString();
+    }
+
+    private static String createConstructorClosingPart(final String indent) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
         final StringBuilder builder = new StringBuilder();
         builder.append(indent);
         builder.append(RCB);
@@ -340,25 +529,55 @@ public final class GeneratorUtil {
         return builder.toString();
     }
 
-    private static String createClassAttributeInitialization(String indent, GeneratedProperty methodParameter) {
+    private static String createClassPropertiesInitialization(final List<GeneratedProperty> properties,
+            final String indent) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (properties == null) {
+            throw new IllegalArgumentException("List of generated class properties can't be null");
+        }
+        final StringBuilder builder = new StringBuilder();
+        for (final GeneratedProperty property : properties) {
+            createClassPropertyInitialization(property, indent);
+        }
+        return builder.toString();
+    }
+
+    private static String createClassPropertyInitialization(final GeneratedProperty property, final String indent) {
+        if (indent == null) {
+            throw new IllegalArgumentException("String with indent can't be null");
+        }
+        if (property == null) {
+            throw new IllegalArgumentException("List of generated class properties can't be null");
+        }
         final StringBuilder builder = new StringBuilder();
         builder.append(indent);
         builder.append(TAB);
         builder.append("this.");
-        builder.append(methodParameter.getName());
+        builder.append(property.getName());
         builder.append(" = ");
-        builder.append(methodParameter.getName());
+        builder.append(property.getName());
         builder.append(SC);
         builder.append(NL);
         return builder.toString();
     }
 
-    private static String createMethodParamDeclaration(GeneratedProperty methodParameter,
-            final Map<String, String> availableImports, String currentPkg) {
+    private static String createMethodPropertyDeclaration(final GeneratedProperty property,
+            final Map<String, String> availableImports, final String currentPkg) {
+        if (property == null) {
+            throw new IllegalArgumentException("Generated property can't be null");
+        }
+        if (availableImports == null) {
+            throw new IllegalArgumentException("Map of available imports can't be null");
+        }
+        if (currentPkg == null) {
+            throw new IllegalArgumentException("String with current package can't be null");
+        }
         final StringBuilder builder = new StringBuilder();
-        builder.append(getExplicitType(methodParameter.getReturnType(), availableImports, currentPkg));
+        builder.append(getExplicitType(property.getReturnType(), availableImports, currentPkg));
         builder.append(GAP);
-        builder.append(methodParameter.getName());
+        builder.append(property.getName());
         return builder.toString();
     }
 
@@ -784,6 +1003,51 @@ public final class GeneratorUtil {
         return false;
     }
 
+    /**
+     * The method returns reference to highest (top parent) Generated Transfer
+     * Object.
+     * 
+     * @param childTransportObject
+     *            is generated transfer object which can be extended by other
+     *            generated transfer object
+     * @return in first case that <code>childTransportObject</code> isn't
+     *         extended then <code>childTransportObject</code> is returned. In
+     *         second case the method is recursive called until first case.
+     */
+    private static GeneratedTransferObject getTopParrentTransportObject(GeneratedTransferObject childTransportObject) {
+        if (childTransportObject == null) {
+            throw new IllegalArgumentException("Parameter childTransportObject can't be null.");
+        }
+        if (childTransportObject.getExtends() == null) {
+            return childTransportObject;
+        } else {
+            return getTopParrentTransportObject(childTransportObject.getExtends());
+        }
+    }
+
+    /**
+     * The method returns the list of the properties of all extending generated
+     * transfer object from <code>genTO</code> to highest parent generated
+     * transfer object
+     * 
+     * @param genTO
+     * @return the list of all properties from actual to highest parent
+     *         generated transfer object. In case when extension exists the
+     *         method is recursive called.
+     */
+    private static List<GeneratedProperty> getPropertiesOfAllParents(GeneratedTransferObject genTO) {
+        List<GeneratedProperty> propertiesOfAllParents = new ArrayList<GeneratedProperty>();
+        if (genTO != null) {
+            final List<GeneratedProperty> allPropertiesOfTO = genTO.getProperties();
+            List<GeneratedProperty> readOnlyPropertiesOfTO = resolveReadOnlyPropertiesFromTO(allPropertiesOfTO);
+            propertiesOfAllParents.addAll(readOnlyPropertiesOfTO);
+            if (genTO.getExtends() != null) {
+                propertiesOfAllParents.addAll(getPropertiesOfAllParents(genTO.getExtends()));
+            }
+        }
+        return propertiesOfAllParents;
+    }
+
     public static String createStaticInicializationBlock(GeneratedTransferObject genTransferObject, String indent) {
 
         final StringBuilder builder = new StringBuilder();
diff --git a/opendaylight/sal/yang-prototype/code-generator/samples/maven-code-gen-sample/src/main/yang/typedef_of_typedef.yang b/opendaylight/sal/yang-prototype/code-generator/samples/maven-code-gen-sample/src/main/yang/typedef_of_typedef.yang
new file mode 100644 (file)
index 0000000..3aa6770
--- /dev/null
@@ -0,0 +1,79 @@
+module typedef_typedef {
+    
+    namespace "urn:typedef:typedef";
+    prefix "sbd";
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    revision 2013-07-09 {
+        
+    }
+
+   typedef byte-type {
+        type bits {
+            bit first-bit {
+                position 10;
+            }
+            bit second-bit {
+                position 20;
+            }
+         }
+    }    
+    
+    
+  typedef typedef-enum-fruit {
+    type enumeration {
+      enum "apple" {
+        value 1;
+        description "gold";
+      }
+      enum "pear" {
+        value 2;
+      }
+    }
+  }    
+    
+    typedef simple-typedef1 {
+       type uint8;
+    }
+    
+    typedef simple-typedef2 {
+        type simple-typedef1;
+    }
+    
+    typedef simple-typedef3 {
+        type simple-typedef2;
+    }
+    
+    typedef simple-typedef4 {
+        type simple-typedef3;
+    }
+    
+    typedef simple-typedef1-1 {
+        type uint16;
+    }    
+
+    
+    typedef union-typedef {
+        type union {
+            type simple-typedef1;
+            type simple-typedef4;
+            type byte-type;
+            type typedef-enum-fruit;
+        }
+    }    
+    
+    typedef extended-typedef-union {
+        type union-typedef;
+    }
+    
+    
+    typedef extended-typedef-simple {
+        type simple-typedef1;
+    }
+    
+    typedef extended-typedef-enum {
+        type typedef-enum-fruit;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractBuilder.java b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/AbstractBuilder.java
new file mode 100644 (file)
index 0000000..786a7ec
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * 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.yang.parser.builder.api;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
+
+/**
+ * Basic implementation of Builder.
+ */
+public abstract class AbstractBuilder implements Builder {
+    protected String moduleName;
+    protected final int line;
+    protected Builder parent;
+
+    protected List<UnknownSchemaNode> unknownNodes;
+    protected final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
+
+    protected AbstractBuilder(final String moduleName, final int line) {
+        this.moduleName = moduleName;
+        this.line = line;
+    }
+
+    @Override
+    public String getModuleName() {
+        return moduleName;
+    }
+
+    @Override
+    public void setModuleName(final String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    @Override
+    public int getLine() {
+        return line;
+    }
+
+    @Override
+    public Builder getParent() {
+        return parent;
+    }
+
+    @Override
+    public void setParent(final Builder parent) {
+        this.parent = parent;
+    }
+
+    @Override
+    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
+        return addedUnknownNodes;
+    }
+
+    @Override
+    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
+        addedUnknownNodes.add(unknownNode);
+    }
+
+    public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {
+        this.unknownNodes = unknownNodes;
+    }
+
+}
index df85c5cbf09fe166630da10f8ae5f3347cabd055..d6867ce73592a3a3511e88ef451628cd915602a7 100644 (file)
@@ -7,26 +7,20 @@
  */
 package org.opendaylight.controller.yang.parser.builder.api;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
 
 import org.opendaylight.controller.yang.common.QName;
 import org.opendaylight.controller.yang.model.api.DataSchemaNode;
 import org.opendaylight.controller.yang.model.api.GroupingDefinition;
-import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
 import org.opendaylight.controller.yang.parser.util.YangParseException;
 
 /**
  * Basic implementation of DataNodeContainerBuilder.
  */
-public abstract class AbstractDataNodeContainerBuilder implements DataNodeContainerBuilder {
-    protected final int line;
+public abstract class AbstractDataNodeContainerBuilder extends AbstractBuilder implements DataNodeContainerBuilder {
     protected final QName qname;
-    protected Builder parent;
 
     protected Set<DataSchemaNode> childNodes;
     protected final Set<DataSchemaNodeBuilder> addedChildNodes = new HashSet<DataSchemaNodeBuilder>();
@@ -34,29 +28,11 @@ public abstract class AbstractDataNodeContainerBuilder implements DataNodeContai
     protected Set<GroupingDefinition> groupings;
     protected final Set<GroupingBuilder> addedGroupings = new HashSet<GroupingBuilder>();
 
-    protected List<UnknownSchemaNode> unknownNodes;
-    protected final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
-
-    protected AbstractDataNodeContainerBuilder(final int line, final QName qname) {
-        this.line = line;
+    protected AbstractDataNodeContainerBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line);
         this.qname = qname;
     }
 
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
-    }
-
     @Override
     public QName getQName() {
         return qname;
@@ -91,9 +67,12 @@ public abstract class AbstractDataNodeContainerBuilder implements DataNodeContai
 
     @Override
     public void addChildNode(DataSchemaNodeBuilder child) {
-        for (DataSchemaNodeBuilder childNode : addedChildNodes) {
-            if (childNode.getQName().getLocalName().equals(child.getQName().getLocalName())) {
-                throw new YangParseException(child.getLine(), "Duplicate node found at line " + childNode.getLine());
+        String childName = child.getQName().getLocalName();
+        for (DataSchemaNodeBuilder addedChildNode : addedChildNodes) {
+            if (addedChildNode.getQName().getLocalName().equals(childName)) {
+                throw new YangParseException(child.getModuleName(), child.getLine(), "Can not add '" + child
+                        + "' to node '" + qname.getLocalName() + "' in module '" + moduleName
+                        + "': node with same name already declared at line " + addedChildNode.getLine());
             }
         }
         addedChildNodes.add(child);
@@ -116,27 +95,16 @@ public abstract class AbstractDataNodeContainerBuilder implements DataNodeContai
     }
 
     @Override
-    public void addGrouping(GroupingBuilder groupingBuilder) {
-        for (GroupingBuilder gb : addedGroupings) {
-            if (gb.getQName().getLocalName().equals(groupingBuilder.getQName().getLocalName())) {
-                throw new YangParseException(groupingBuilder.getLine(), "Duplicate node found at line " + gb.getLine());
+    public void addGrouping(GroupingBuilder grouping) {
+        String groupingName = grouping.getQName().getLocalName();
+        for (GroupingBuilder addedGrouping : addedGroupings) {
+            if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
+                throw new YangParseException(grouping.getModuleName(), grouping.getLine(), "Can not add '" + grouping
+                        + "': grouping with same name already declared in module '" + moduleName + "' at line "
+                        + addedGrouping.getLine());
             }
         }
-        addedGroupings.add(groupingBuilder);
-    }
-
-    @Override
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
-        return addedUnknownNodes;
-    }
-
-    @Override
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
-        addedUnknownNodes.add(unknownNode);
-    }
-
-    public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {
-        this.unknownNodes = unknownNodes;
+        addedGroupings.add(grouping);
     }
 
 }
index a786cd9ad754c954803937df3b8890d4afa47c05..2727bc95338dea28a4af59f9296b023869ccd7e0 100644 (file)
@@ -7,53 +7,33 @@
  */\r
 package org.opendaylight.controller.yang.parser.builder.api;\r
 \r
-import java.util.ArrayList;\r
 import java.util.List;\r
 \r
 import org.opendaylight.controller.yang.common.QName;\r
 import org.opendaylight.controller.yang.model.api.SchemaPath;\r
 import org.opendaylight.controller.yang.model.api.Status;\r
 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;\r
-import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder;\r
 \r
 /**\r
  * Basic implementation of SchemaNodeBuilder.\r
  */\r
-public abstract class AbstractSchemaNodeBuilder implements SchemaNodeBuilder {\r
-    protected final int line;\r
+public abstract class AbstractSchemaNodeBuilder extends AbstractBuilder implements SchemaNodeBuilder {\r
     protected final QName qname;\r
-    protected Builder parent;\r
     protected SchemaPath schemaPath;\r
     protected String description;\r
     protected String reference;\r
     protected Status status = Status.CURRENT;\r
     protected List<UnknownSchemaNode> unknownNodes;\r
-    protected final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();\r
 \r
-    protected AbstractSchemaNodeBuilder(final int line, final QName qname) {\r
-        this.line = line;\r
+    protected AbstractSchemaNodeBuilder(final String moduleName, final int line, final QName qname) {\r
+        super(moduleName, line);\r
         this.qname = qname;\r
     }\r
 \r
-    @Override\r
-    public int getLine() {\r
-        return line;\r
-    }\r
-\r
     public QName getQName() {\r
         return qname;\r
     }\r
 \r
-    @Override\r
-    public Builder getParent() {\r
-        return parent;\r
-    }\r
-\r
-    @Override\r
-    public void setParent(final Builder parent) {\r
-        this.parent = parent;\r
-    }\r
-\r
     @Override\r
     public SchemaPath getPath() {\r
         return schemaPath;\r
@@ -96,16 +76,6 @@ public abstract class AbstractSchemaNodeBuilder implements SchemaNodeBuilder {
         }\r
     }\r
 \r
-    @Override\r
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {\r
-        return addedUnknownNodes;\r
-    }\r
-\r
-    @Override\r
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {\r
-        addedUnknownNodes.add(unknownNode);\r
-    }\r
-\r
     public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {\r
         this.unknownNodes = unknownNodes;\r
     }\r
index 3e8dc6c8b09f6c817c568e90f969789be1c99592..23ded94c4039a6de64a5e797184daf67e1d0d2d3 100644 (file)
@@ -7,46 +7,22 @@
  */
 package org.opendaylight.controller.yang.parser.builder.api;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.opendaylight.controller.yang.common.QName;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
-import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
 
 /**
  * Basic implementation for TypeAwareBuilder builders.
  */
-public abstract class AbstractTypeAwareBuilder implements TypeAwareBuilder {
-    protected final int line;
+public abstract class AbstractTypeAwareBuilder extends AbstractBuilder implements TypeAwareBuilder {
     protected final QName qname;
-    protected Builder parent;
     protected TypeDefinition<?> type;
     protected TypeDefinitionBuilder typedef;
-    protected List<UnknownSchemaNode> unknownNodes;
-    protected final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
 
-    public AbstractTypeAwareBuilder(final int line, final QName qname) {
-        this.line = line;
+    public AbstractTypeAwareBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line);
         this.qname = qname;
     }
 
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
-    }
-
     @Override
     public QName getQName() {
         return qname;
@@ -74,18 +50,4 @@ public abstract class AbstractTypeAwareBuilder implements TypeAwareBuilder {
         this.type = null;
     }
 
-    @Override
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
-        return addedUnknownNodes;
-    }
-
-    @Override
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
-        addedUnknownNodes.add(unknownNode);
-    }
-
-    public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {
-        this.unknownNodes = unknownNodes;
-    }
-
 }
index eb23eaba106e68888c754ea3ca87f5d121929d27..b849f20d2fb5c4da004ab11be3c6fa334aba0731 100644 (file)
@@ -16,6 +16,20 @@ import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBui
  */
 public interface Builder {
 
+    /**
+     * Get name of module in which this node is declared.
+     *
+     * @return module name
+     */
+    String getModuleName();
+
+    /**
+     * Set name of module in which this node is declared.
+     *
+     * @param moduleName
+     */
+    void setModuleName(String moduleName);
+
     /**
      * Get current line in yang file.
      *
index 42f714b8fcc33d741e8ea508f138f2479da3c17f..6b6063cc953a1063758e7a4f1ed7bd304cd20dd7 100644 (file)
@@ -31,15 +31,15 @@ public final class AnyXmlBuilder extends AbstractSchemaNodeBuilder implements Da
     private boolean augmenting;
     private boolean addedByUses;
 
-    public AnyXmlBuilder(final int line, final QName qname, final SchemaPath schemaPath) {
-        super(line, qname);
+    public AnyXmlBuilder(final String moduleName, final int line, final QName qname, final SchemaPath schemaPath) {
+        super(moduleName, line, qname);
         this.schemaPath = schemaPath;
         instance = new AnyXmlSchemaNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public AnyXmlBuilder(final AnyXmlBuilder builder) {
-        super(builder.getLine(), builder.getQName());
+        super(builder.getModuleName(), builder.getLine(), builder.getQName());
         parent = builder.getParent();
         instance = new AnyXmlSchemaNodeImpl(qname);
         constraints = builder.getConstraints();
index 6d8b78919bb7d9689d98bc5ecb04e8658e4b1bf6..cdb751f81bed1a703a60991d1fb16693bc4b2d11 100644 (file)
@@ -54,8 +54,8 @@ public final class AugmentationSchemaBuilderImpl extends AbstractDataNodeContain
     private final Set<UsesNodeBuilder> usesNodes = new HashSet<UsesNodeBuilder>();
     private boolean resolved;
 
-    AugmentationSchemaBuilderImpl(final int line, final String augmentTargetStr) {
-        super(line, null);
+    AugmentationSchemaBuilderImpl(final String moduleName, final int line, final String augmentTargetStr) {
+        super(moduleName, line, null);
         this.augmentTargetStr = augmentTargetStr;
         final SchemaPath targetPath = ParserListenerUtils.parseAugmentPath(augmentTargetStr);
         dirtyAugmentTarget = targetPath;
@@ -74,7 +74,7 @@ public final class AugmentationSchemaBuilderImpl extends AbstractDataNodeContain
 
     @Override
     public void addGrouping(GroupingBuilder grouping) {
-        throw new YangParseException(line, "augment can not contains grouping statement");
+        throw new YangParseException(moduleName, line, "augment can not contains grouping statement");
     }
 
     @Override
@@ -158,7 +158,7 @@ public final class AugmentationSchemaBuilderImpl extends AbstractDataNodeContain
 
     @Override
     public void addTypedef(TypeDefinitionBuilder type) {
-        throw new YangParseException(line, "Augmentation can not contains typedef statement.");
+        throw new YangParseException(moduleName, line, "Augmentation can not contains typedef statement.");
     }
 
     @Override
index 0fcfd339a583f95eb9fa7570404f3651922e0f58..1cd54cae62ab2a93ba050351fe90388267632bba 100644 (file)
@@ -29,6 +29,7 @@ import org.opendaylight.controller.yang.parser.builder.api.DataSchemaNodeBuilder
 import org.opendaylight.controller.yang.parser.builder.api.GroupingMember;
 import org.opendaylight.controller.yang.parser.util.Comparators;
 import org.opendaylight.controller.yang.parser.util.ParserUtils;
+import org.opendaylight.controller.yang.parser.util.YangParseException;
 
 public final class ChoiceBuilder extends AbstractSchemaNodeBuilder implements DataSchemaNodeBuilder,
         AugmentationTargetBuilder, GroupingMember {
@@ -46,14 +47,14 @@ public final class ChoiceBuilder extends AbstractSchemaNodeBuilder implements Da
     private final Set<ChoiceCaseBuilder> addedCases = new HashSet<ChoiceCaseBuilder>();
     private String defaultCase;
 
-    public ChoiceBuilder(final int line, final QName qname) {
-        super(line, qname);
+    public ChoiceBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new ChoiceNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public ChoiceBuilder(ChoiceBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         parent = b.getParent();
         instance = new ChoiceNodeImpl(qname);
         constraints = b.getConstraints();
@@ -126,20 +127,41 @@ public final class ChoiceBuilder extends AbstractSchemaNodeBuilder implements Da
         return addedCases;
     }
 
-    public void addChildNode(DataSchemaNodeBuilder childNode) {
-        if (!(childNode instanceof ChoiceCaseBuilder)) {
-            ChoiceCaseBuilder caseBuilder = new ChoiceCaseBuilder(childNode.getLine(), childNode.getQName());
-            if (childNode.isAugmenting()) {
+    /**
+     * Add case node to this choice.
+     *
+     * If node is not declared with 'case' keyword, create new case builder and
+     * make this node child of newly created case.
+     *
+     * @param caseNode
+     *            case node
+     */
+    public void addCase(DataSchemaNodeBuilder caseNode) {
+        String newCaseName = caseNode.getQName().getLocalName();
+        for (ChoiceCaseBuilder addedCase : addedCases) {
+            if (addedCase.getQName().getLocalName().equals(newCaseName)) {
+                throw new YangParseException(caseNode.getModuleName(), caseNode.getLine(), "Can not add '" + caseNode
+                        + "' to node '" + qname.getLocalName() + "' in module '" + moduleName
+                        + "': case with same name already declared at line " + addedCase.getLine());
+            }
+        }
+
+        if (caseNode instanceof ChoiceCaseBuilder) {
+            addedCases.add((ChoiceCaseBuilder) caseNode);
+        } else {
+            ChoiceCaseBuilder caseBuilder = new ChoiceCaseBuilder(caseNode.getModuleName(), caseNode.getLine(),
+                    caseNode.getQName());
+            if (caseNode.isAugmenting()) {
+                // if node is added by augmentation, set case builder augmenting
+                // as true and node augmenting as false
                 caseBuilder.setAugmenting(true);
-                childNode.setAugmenting(false);
+                caseNode.setAugmenting(false);
             }
-            caseBuilder.setPath(childNode.getPath());
-            SchemaPath newPath = ParserUtils.createSchemaPath(childNode.getPath(), childNode.getQName().getLocalName());
-            childNode.setPath(newPath);
-            caseBuilder.addChildNode(childNode);
+            caseBuilder.setPath(caseNode.getPath());
+            SchemaPath newPath = ParserUtils.createSchemaPath(caseNode.getPath(), caseNode.getQName().getLocalName());
+            caseNode.setPath(newPath);
+            caseBuilder.addChildNode(caseNode);
             addedCases.add(caseBuilder);
-        } else {
-            addedCases.add((ChoiceCaseBuilder) childNode);
         }
     }
 
index 46821b2e10cfc0bf3301144092665e6600f0b445..c5282bc0eafd314449612108742f607bc7347f86 100644 (file)
@@ -45,10 +45,10 @@ public final class ChoiceCaseBuilder extends AbstractDataNodeContainerBuilder im
     // AugmentationTarget args
     private final Set<AugmentationSchemaBuilder> addedAugmentations = new HashSet<AugmentationSchemaBuilder>();
 
-    ChoiceCaseBuilder(final int line, final QName qname) {
-        super(line, qname);
+    ChoiceCaseBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new ChoiceCaseNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     @Override
@@ -165,7 +165,7 @@ public final class ChoiceCaseBuilder extends AbstractDataNodeContainerBuilder im
 
     @Override
     public void addTypedef(TypeDefinitionBuilder typedefBuilder) {
-        throw new YangParseException(line, "Can not add type definition to choice case.");
+        throw new YangParseException(moduleName, line, "Can not add type definition to choice case.");
     }
 
     @Override
@@ -175,7 +175,7 @@ public final class ChoiceCaseBuilder extends AbstractDataNodeContainerBuilder im
 
     @Override
     public void setConfiguration(final Boolean configuration) {
-        throw new YangParseException(line, "Can not add config statement to choice case.");
+        throw new YangParseException(moduleName, line, "Can not add config statement to choice case.");
     }
 
     @Override
index 5ec825b382072ac642c32a466a040b5ac8ae4030..b2f1dff3a52dacc93e80b54e613c611cd3f787ff 100644 (file)
@@ -16,21 +16,19 @@ import org.opendaylight.controller.yang.model.api.ConstraintDefinition;
 import org.opendaylight.controller.yang.model.api.MustDefinition;
 import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
 import org.opendaylight.controller.yang.model.util.RevisionAwareXPathImpl;
-import org.opendaylight.controller.yang.parser.builder.api.Builder;
+import org.opendaylight.controller.yang.parser.builder.api.AbstractBuilder;
 import org.opendaylight.controller.yang.parser.util.YangParseException;
 
-public final class ConstraintsBuilder implements Builder {
+public final class ConstraintsBuilder extends AbstractBuilder {
     private final ConstraintDefinitionImpl instance;
-    private final int line;
-    private Builder parent;
     private final Set<MustDefinition> mustDefinitions;
     private String whenCondition;
     private boolean mandatory;
     private Integer min;
     private Integer max;
 
-    ConstraintsBuilder(final int line) {
-        this.line = line;
+    ConstraintsBuilder(final String moduleName, final int line) {
+        super(moduleName, line);
         instance = new ConstraintDefinitionImpl();
         mustDefinitions = new HashSet<MustDefinition>();
     }
@@ -51,24 +49,9 @@ public final class ConstraintsBuilder implements Builder {
         return instance;
     }
 
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
-    }
-
     @Override
     public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
-        throw new YangParseException(line, "Can not add unknown node to constraints.");
+        throw new YangParseException(moduleName, line, "Can not add unknown node to constraints.");
     }
 
     @Override
@@ -116,7 +99,6 @@ public final class ConstraintsBuilder implements Builder {
         this.mandatory = mandatory;
     }
 
-
     private final class ConstraintDefinitionImpl implements ConstraintDefinition {
         private RevisionAwareXPath whenCondition;
         private Set<MustDefinition> mustConstraints;
index c85c12fcd5f6bcbdd6c593749c9c226bc4c3050c..0bc56d430a97d83d7a2944ddd9938bc3907126d4 100644 (file)
@@ -36,6 +36,7 @@ import org.opendaylight.controller.yang.parser.builder.api.GroupingMember;
 import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.UsesNodeBuilder;
 import org.opendaylight.controller.yang.parser.util.Comparators;
+import org.opendaylight.controller.yang.parser.util.YangParseException;
 
 public final class ContainerSchemaNodeBuilder extends AbstractDataNodeContainerBuilder implements
         AugmentationTargetBuilder, DataSchemaNodeBuilder, GroupingMember {
@@ -63,15 +64,16 @@ public final class ContainerSchemaNodeBuilder extends AbstractDataNodeContainerB
     // ContainerSchemaNode args
     private boolean presence;
 
-    public ContainerSchemaNodeBuilder(final int line, final QName qname, final SchemaPath schemaPath) {
-        super(line, qname);
+    public ContainerSchemaNodeBuilder(final String moduleName, final int line, final QName qname,
+            final SchemaPath schemaPath) {
+        super(moduleName, line, qname);
         this.schemaPath = schemaPath;
         instance = new ContainerSchemaNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public ContainerSchemaNodeBuilder(final ContainerSchemaNodeBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         instance = new ContainerSchemaNodeImpl(b.getQName());
         constraints = b.getConstraints();
         schemaPath = b.getPath();
@@ -116,7 +118,7 @@ public final class ContainerSchemaNodeBuilder extends AbstractDataNodeContainerB
 
             // CHILD NODES
             final Map<QName, DataSchemaNode> childs = new TreeMap<QName, DataSchemaNode>(Comparators.QNAME_COMP);
-            if (childNodes == null) {
+            if (childNodes == null || childNodes.isEmpty()) {
                 for (DataSchemaNodeBuilder node : addedChildNodes) {
                     childs.put(node.getQName(), node.build());
                 }
@@ -194,6 +196,11 @@ public final class ContainerSchemaNodeBuilder extends AbstractDataNodeContainerB
 
     @Override
     public void addTypedef(final TypeDefinitionBuilder type) {
+        String typeName = type.getQName().getLocalName();
+        for (TypeDefinitionBuilder addedTypedef : addedTypedefs) {
+            throw new YangParseException(moduleName, type.getLine(), "Can not add typedef '" + typeName
+                    + "': typedef with same name already declared at line " + addedTypedef.getLine());
+        }
         addedTypedefs.add(type);
     }
 
index 42347cbba364b35f1129fe8bfa6e52eac1404864..3bc9879de7213cf919394490098e678bf6b22d22 100644 (file)
@@ -15,15 +15,13 @@ import org.opendaylight.controller.yang.model.api.Deviation;
 import org.opendaylight.controller.yang.model.api.Deviation.Deviate;
 import org.opendaylight.controller.yang.model.api.SchemaPath;
 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.controller.yang.parser.builder.api.Builder;
+import org.opendaylight.controller.yang.parser.builder.api.AbstractBuilder;
 import org.opendaylight.controller.yang.parser.util.Comparators;
 import org.opendaylight.controller.yang.parser.util.ParserListenerUtils;
 import org.opendaylight.controller.yang.parser.util.YangParseException;
 
-public final class DeviationBuilder implements Builder {
-    private final int line;
+public final class DeviationBuilder extends AbstractBuilder {
     private final String targetPathStr;
-    private Builder parent;
     private boolean isBuilt;
     private final DeviationImpl instance;
 
@@ -31,11 +29,12 @@ public final class DeviationBuilder implements Builder {
     private String reference;
     private final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
 
-    DeviationBuilder(final int line, final String targetPathStr) {
-        if(!targetPathStr.startsWith("/")) {
-            throw new YangParseException(line, "Deviation argument string must be an absolute schema node identifier.");
+    DeviationBuilder(final String moduleName, final int line, final String targetPathStr) {
+        super(moduleName, line);
+        if (!targetPathStr.startsWith("/")) {
+            throw new YangParseException(moduleName, line,
+                    "Deviation argument string must be an absolute schema node identifier.");
         }
-        this.line = line;
         this.targetPathStr = targetPathStr;
         this.targetPath = ParserListenerUtils.parseAugmentPath(targetPathStr);
         instance = new DeviationImpl();
@@ -43,11 +42,11 @@ public final class DeviationBuilder implements Builder {
 
     @Override
     public Deviation build() {
-        if(targetPath == null) {
-            throw new YangParseException(line, "Unresolved deviation target");
+        if (targetPath == null) {
+            throw new YangParseException(moduleName, line, "Unresolved deviation target");
         }
 
-        if(!isBuilt) {
+        if (!isBuilt) {
             instance.setTargetPath(targetPath);
             instance.setReference(reference);
 
@@ -65,31 +64,6 @@ public final class DeviationBuilder implements Builder {
         return instance;
     }
 
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
-    }
-
-    @Override
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
-        return addedUnknownNodes;
-    }
-
-    @Override
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
-        addedUnknownNodes.add(unknownNode);
-    }
-
     public SchemaPath getTargetPath() {
         return targetPath;
     }
@@ -108,8 +82,7 @@ public final class DeviationBuilder implements Builder {
         } else if ("delete".equals(deviate)) {
             instance.setDeviate(Deviate.DELETE);
         } else {
-            throw new YangParseException(line,
-                    "Unsupported type of 'deviate' statement: " + deviate);
+            throw new YangParseException(moduleName, line, "Unsupported type of 'deviate' statement: " + deviate);
         }
     }
 
@@ -173,12 +146,9 @@ public final class DeviationBuilder implements Builder {
         public int hashCode() {
             final int prime = 31;
             int result = 1;
-            result = prime * result
-                    + ((targetPath == null) ? 0 : targetPath.hashCode());
-            result = prime * result
-                    + ((deviate == null) ? 0 : deviate.hashCode());
-            result = prime * result
-                    + ((reference == null) ? 0 : reference.hashCode());
+            result = prime * result + ((targetPath == null) ? 0 : targetPath.hashCode());
+            result = prime * result + ((deviate == null) ? 0 : deviate.hashCode());
+            result = prime * result + ((reference == null) ? 0 : reference.hashCode());
             return result;
         }
 
@@ -220,8 +190,7 @@ public final class DeviationBuilder implements Builder {
 
         @Override
         public String toString() {
-            StringBuilder sb = new StringBuilder(
-                    DeviationImpl.class.getSimpleName());
+            StringBuilder sb = new StringBuilder(DeviationImpl.class.getSimpleName());
             sb.append("[");
             sb.append("targetPath=" + targetPath);
             sb.append(", deviate=" + deviate);
index fbd55ab7d9fda8249b963b654be0bf03bab6aa84..93a34e1050052b9f6e2dab726d89ba9ca42ddd54 100644 (file)
@@ -23,8 +23,8 @@ public final class ExtensionBuilder extends AbstractSchemaNodeBuilder {
     private boolean isBuilt;
     private final ExtensionDefinitionImpl instance;
 
-    ExtensionBuilder(final int line, final QName qname) {
-        super(line, qname);
+    ExtensionBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new ExtensionDefinitionImpl(qname);
     }
 
index 53129f100b8622515d759728cd278ef7801d397a..dd3fd11e925246f23373c3490f04cf2260fbd068 100644 (file)
@@ -23,8 +23,8 @@ public final class FeatureBuilder extends AbstractSchemaNodeBuilder {
     private boolean isBuilt;
     private final FeatureDefinitionImpl instance;
 
-    FeatureBuilder(final int line, final QName qname) {
-        super(line, qname);
+    FeatureBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new FeatureDefinitionImpl(qname);
     }
 
index 20503488ce9802e019c99bd8e46f82e929d7f695..8a8f1211cb474c3894852d566abd6197a34b13f5 100644 (file)
@@ -9,11 +9,11 @@ package org.opendaylight.controller.yang.parser.builder.impl;
 
 import java.util.ArrayList;
 import java.util.Collections;
-import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.TreeMap;
 import java.util.TreeSet;
 
 import org.opendaylight.controller.yang.common.QName;
@@ -24,51 +24,38 @@ import org.opendaylight.controller.yang.model.api.Status;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.controller.yang.model.api.UsesNode;
-import org.opendaylight.controller.yang.parser.builder.api.Builder;
+import org.opendaylight.controller.yang.parser.builder.api.AbstractDataNodeContainerBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.DataSchemaNodeBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.GroupingBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.UsesNodeBuilder;
 import org.opendaylight.controller.yang.parser.util.Comparators;
+import org.opendaylight.controller.yang.parser.util.YangParseException;
 
-public final class GroupingBuilderImpl implements GroupingBuilder {
-    private Builder parent;
+public final class GroupingBuilderImpl extends AbstractDataNodeContainerBuilder implements GroupingBuilder {
     private boolean isBuilt;
     private final GroupingDefinitionImpl instance;
-    private final int line;
-    private final QName qname;
     private SchemaPath schemaPath;
     private String description;
     private String reference;
     private Status status = Status.CURRENT;
     private boolean addedByUses;
 
-    private Set<DataSchemaNode> childNodes;
-    private final Set<DataSchemaNodeBuilder> addedChildNodes = new HashSet<DataSchemaNodeBuilder>();
-
-    private Set<GroupingDefinition> groupings;
-    private final Set<GroupingBuilder> addedGroupings = new HashSet<GroupingBuilder>();
-
     private Set<TypeDefinition<?>> typedefs;
     private final Set<TypeDefinitionBuilder> addedTypedefs = new HashSet<TypeDefinitionBuilder>();
 
     private Set<UsesNode> usesNodes;
     private final Set<UsesNodeBuilder> addedUsesNodes = new HashSet<UsesNodeBuilder>();
 
-    private List<UnknownSchemaNode> unknownNodes;
-    private final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
-
-    public GroupingBuilderImpl(final QName qname, final int line) {
-        this.qname = qname;
+    public GroupingBuilderImpl(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new GroupingDefinitionImpl(qname);
-        this.line = line;
     }
 
     public GroupingBuilderImpl(GroupingBuilder builder) {
-        qname = builder.getQName();
+        super(builder.getModuleName(), builder.getLine(), builder.getQName());
         parent = builder.getParent();
         instance = new GroupingDefinitionImpl(qname);
-        line = builder.getLine();
         schemaPath = builder.getPath();
         description = builder.getDescription();
         reference = builder.getReference();
@@ -92,8 +79,8 @@ public final class GroupingBuilderImpl implements GroupingBuilder {
             instance.setAddedByUses(addedByUses);
 
             // CHILD NODES
-            final Map<QName, DataSchemaNode> childs = new HashMap<QName, DataSchemaNode>();
-            if (childNodes == null) {
+            final Map<QName, DataSchemaNode> childs = new TreeMap<QName, DataSchemaNode>(Comparators.QNAME_COMP);
+            if (childNodes == null || childNodes.isEmpty()) {
                 for (DataSchemaNodeBuilder node : addedChildNodes) {
                     childs.put(node.getQName(), node.build());
                 }
@@ -147,25 +134,6 @@ public final class GroupingBuilderImpl implements GroupingBuilder {
         return instance;
     }
 
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
-    }
-
-    @Override
-    public QName getQName() {
-        return qname;
-    }
 
     @Override
     public Set<TypeDefinitionBuilder> getTypeDefinitionBuilders() {
@@ -174,6 +142,11 @@ public final class GroupingBuilderImpl implements GroupingBuilder {
 
     @Override
     public void addTypedef(final TypeDefinitionBuilder type) {
+        String typeName = type.getQName().getLocalName();
+        for (TypeDefinitionBuilder addedTypedef : addedTypedefs) {
+            throw new YangParseException(moduleName, type.getLine(), "Can not add typedef '" + typeName
+                    + "': typedef with same name already declared at line " + addedTypedef.getLine());
+        }
         addedTypedefs.add(type);
     }
 
@@ -231,54 +204,6 @@ public final class GroupingBuilderImpl implements GroupingBuilder {
         this.addedByUses = addedByUses;
     }
 
-    @Override
-    public Set<DataSchemaNode> getChildNodes() {
-        return childNodes;
-    }
-
-    @Override
-    public void addChildNode(final DataSchemaNodeBuilder childNode) {
-        addedChildNodes.add(childNode);
-    }
-
-    @Override
-    public Set<DataSchemaNodeBuilder> getChildNodeBuilders() {
-        return addedChildNodes;
-    }
-
-    @Override
-    public DataSchemaNodeBuilder getDataChildByName(final String name) {
-        for(DataSchemaNodeBuilder child : addedChildNodes) {
-            if(child.getQName().getLocalName().equals(name)) {
-                return child;
-            }
-        }
-        return null;
-    }
-
-    public void setChildNodes(final Set<DataSchemaNode> childNodes) {
-        this.childNodes = childNodes;
-    }
-
-    @Override
-    public Set<GroupingDefinition> getGroupings() {
-        return Collections.emptySet();
-    }
-
-    @Override
-    public Set<GroupingBuilder> getGroupingBuilders() {
-        return addedGroupings;
-    }
-
-    @Override
-    public void addGrouping(final GroupingBuilder grouping) {
-        addedGroupings.add(grouping);
-    }
-
-    public void setGroupings(final Set<GroupingDefinition> groupings) {
-        this.groupings = groupings;
-    }
-
     @Override
     public Set<UsesNodeBuilder> getUses() {
         return addedUsesNodes;
@@ -293,20 +218,6 @@ public final class GroupingBuilderImpl implements GroupingBuilder {
         this.usesNodes = usesNodes;
     }
 
-    @Override
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
-        return addedUnknownNodes;
-    }
-
-    @Override
-    public void addUnknownNodeBuilder(final UnknownSchemaNodeBuilder unknownNode) {
-        addedUnknownNodes.add(unknownNode);
-    }
-
-    public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {
-        this.unknownNodes = unknownNodes;
-    }
-
     @Override
     public String toString() {
         return "grouping " + qname.getLocalName();
index 61ad3a74dd264459761537e308acf8c7ebed89e4..2e7c495d9eeebf08bb285f9c4f7493eca580b0c1 100644 (file)
@@ -26,8 +26,8 @@ public final class IdentitySchemaNodeBuilder extends AbstractSchemaNodeBuilder {
     private IdentitySchemaNode baseIdentity;
     private String baseIdentityName;
 
-    IdentitySchemaNodeBuilder(final int line, final QName qname) {
-        super(line, qname);
+    IdentitySchemaNodeBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new IdentitySchemaNodeImpl(qname);
     }
 
index 43922fa71e80e1080c8f1356bda8dc450e26d781..ca6002930e8bbf7df185cacb3c1674493d4550e0 100644 (file)
@@ -36,8 +36,8 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
     private final SchemaPath schemaPath;
     private QName baseQName;
 
-    IdentityrefTypeBuilder(final String baseString, final SchemaPath schemaPath, final int line) {
-        super(line, null);
+    IdentityrefTypeBuilder(final String moduleName, final int line, final String baseString, final SchemaPath schemaPath) {
+        super(moduleName, line, null);
         this.baseString = baseString;
         this.schemaPath = schemaPath;
     }
@@ -67,32 +67,32 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setType(final TypeDefinition<?> type) {
-        throw new YangParseException(line, "Can not set type to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set type to " + NAME);
     }
 
     @Override
     public void setTypedef(final TypeDefinitionBuilder tdb) {
-        throw new YangParseException(line, "Can not set type to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set type to " + NAME);
     }
 
     @Override
     public void setPath(final SchemaPath schemaPath) {
-        throw new YangParseException(line, "Can not set path to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set path to " + NAME);
     }
 
     @Override
     public void setDescription(final String description) {
-        throw new YangParseException(line, "Can not set description to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set description to " + NAME);
     }
 
     @Override
     public void setReference(final String reference) {
-        throw new YangParseException(line, "Can not set reference to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set reference to " + NAME);
     }
 
     @Override
     public void setStatus(final Status status) {
-        throw new YangParseException(line, "Can not set status to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set status to " + NAME);
     }
 
     @Override
@@ -102,7 +102,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setAddedByUses(final boolean addedByUses) {
-        throw new YangParseException(line, "Identityref type can not be added by uses.");
+        throw new YangParseException(moduleName, line, "Identityref type can not be added by uses.");
     }
 
     @Override
@@ -112,7 +112,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void addUnknownNodeBuilder(final UnknownSchemaNodeBuilder unknownNode) {
-        throw new YangParseException(line, "Can not add unknown node to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not add unknown node to " + NAME);
     }
 
     @Override
@@ -147,7 +147,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setRanges(List<RangeConstraint> ranges) {
-        throw new YangParseException(line, "Can not set ranges to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set ranges to " + NAME);
     }
 
     @Override
@@ -157,7 +157,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setLengths(List<LengthConstraint> lengths) {
-        throw new YangParseException(line, "Can not set lengths to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set lengths to " + NAME);
     }
 
     @Override
@@ -167,7 +167,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setPatterns(List<PatternConstraint> patterns) {
-        throw new YangParseException(line, "Can not set patterns to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set patterns to " + NAME);
     }
 
     @Override
@@ -177,7 +177,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setFractionDigits(Integer fractionDigits) {
-        throw new YangParseException(line, "Can not set fraction digits to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set fraction digits to " + NAME);
     }
 
     @Override
@@ -192,7 +192,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setDefaultValue(Object defaultValue) {
-        throw new YangParseException(line, "Can not set default value to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set default value to " + NAME);
     }
 
     @Override
@@ -202,7 +202,7 @@ public final class IdentityrefTypeBuilder extends AbstractTypeAwareBuilder imple
 
     @Override
     public void setUnits(String units) {
-        throw new YangParseException(line, "Can not set units to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set units to " + NAME);
     }
 
     @Override
index dcbe1dd432a7a1576af19899d60004268cac1f12..8e11ad22170f59da14ce98fb3869fe7ab6eee03a 100644 (file)
@@ -40,15 +40,16 @@ public final class LeafListSchemaNodeBuilder extends AbstractTypeAwareBuilder im
     // LeafListSchemaNode args
     private boolean userOrdered;
 
-    public LeafListSchemaNodeBuilder(final int line, final QName qname, final SchemaPath schemaPath) {
-        super(line, qname);
+    public LeafListSchemaNodeBuilder(final String moduleName, final int line, final QName qname,
+            final SchemaPath schemaPath) {
+        super(moduleName, line, qname);
         this.schemaPath = schemaPath;
         instance = new LeafListSchemaNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public LeafListSchemaNodeBuilder(final LeafListSchemaNodeBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         instance = new LeafListSchemaNodeImpl(qname);
 
         type = b.getType();
index 2ab6407f256a59cec2e9314f0b3f4f3228532cb9..5c1da11afa29af161628a8374324076c85e66eed 100644 (file)
@@ -41,15 +41,15 @@ public final class LeafSchemaNodeBuilder extends AbstractTypeAwareBuilder implem
     private String defaultStr;
     private String unitsStr;
 
-    public LeafSchemaNodeBuilder(final QName qname, final SchemaPath schemaPath, final int line) {
-        super(line, qname);
+    public LeafSchemaNodeBuilder(final String moduleName, final int line, final QName qname, final SchemaPath schemaPath) {
+        super(moduleName, line, qname);
         this.schemaPath = schemaPath;
         instance = new LeafSchemaNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public LeafSchemaNodeBuilder(final LeafSchemaNodeBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         instance = new LeafSchemaNodeImpl(qname);
         constraints = b.getConstraints();
         schemaPath = b.getPath();
index 9fc297e2ba1ce4367034ee13acd0973c5c618d11..5e369d08263909913a10db0458dd739fa0449ebe 100644 (file)
@@ -36,6 +36,7 @@ import org.opendaylight.controller.yang.parser.builder.api.GroupingMember;
 import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.UsesNodeBuilder;
 import org.opendaylight.controller.yang.parser.util.Comparators;
+import org.opendaylight.controller.yang.parser.util.YangParseException;
 
 public final class ListSchemaNodeBuilder extends AbstractDataNodeContainerBuilder implements DataSchemaNodeBuilder,
         AugmentationTargetBuilder, GroupingMember {
@@ -63,15 +64,15 @@ public final class ListSchemaNodeBuilder extends AbstractDataNodeContainerBuilde
     private List<QName> keyDefinition = Collections.emptyList();
     private boolean userOrdered;
 
-    public ListSchemaNodeBuilder(final int line, final QName qname, final SchemaPath schemaPath) {
-        super(line, qname);
+    public ListSchemaNodeBuilder(final String moduleName, final int line, final QName qname, final SchemaPath schemaPath) {
+        super(moduleName, line, qname);
         this.schemaPath = schemaPath;
         instance = new ListSchemaNodeImpl(qname);
-        constraints = new ConstraintsBuilder(line);
+        constraints = new ConstraintsBuilder(moduleName, line);
     }
 
     public ListSchemaNodeBuilder(final ListSchemaNodeBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         instance = new ListSchemaNodeImpl(b.getQName());
         constraints = b.getConstraints();
         schemaPath = b.getPath();
@@ -112,7 +113,7 @@ public final class ListSchemaNodeBuilder extends AbstractDataNodeContainerBuilde
 
             // CHILD NODES
             final Map<QName, DataSchemaNode> childs = new TreeMap<QName, DataSchemaNode>(Comparators.QNAME_COMP);
-            if (childNodes == null) {
+            if (childNodes == null || childNodes.isEmpty()) {
                 for (DataSchemaNodeBuilder node : addedChildNodes) {
                     childs.put(node.getQName(), node.build());
                 }
@@ -190,6 +191,11 @@ public final class ListSchemaNodeBuilder extends AbstractDataNodeContainerBuilde
 
     @Override
     public void addTypedef(final TypeDefinitionBuilder type) {
+        String typeName = type.getQName().getLocalName();
+        for (TypeDefinitionBuilder addedTypedef : addedTypedefs) {
+            throw new YangParseException(moduleName, type.getLine(), "Can not add typedef '" + typeName
+                    + "': typedef with same name already declared at line " + addedTypedef.getLine());
+        }
         addedTypedefs.add(type);
     }
 
index a3409c5b77c0e64616437ac532512db7f1af6133..f424bcfdf939cfc14b9d9dcd8bd3dc066f0e96bc 100644 (file)
@@ -82,7 +82,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     private final List<UnknownSchemaNodeBuilder> allUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
 
     public ModuleBuilder(final String name) {
-        super(0, null);
+        super(name, 0, null);
         this.name = name;
         instance = new ModuleImpl(name);
     }
@@ -320,85 +320,94 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     public ExtensionBuilder addExtension(final QName qname, final int line) {
-        final ExtensionBuilder builder = new ExtensionBuilder(line, qname);
+        final String extName = qname.getLocalName();
+        for (ExtensionBuilder addedExtension : addedExtensions) {
+            if (addedExtension.getQName().getLocalName().equals(extName)) {
+                throw new YangParseException(moduleName, line, "Can not add extension '" + extName
+                        + "': extension with same name already declared at line " + addedExtension.getLine());
+            }
+        }
+        final ExtensionBuilder builder = new ExtensionBuilder(name, line, qname);
         addedExtensions.add(builder);
         return builder;
     }
 
-    public ContainerSchemaNodeBuilder addContainerNode(final int line, final QName containerName,
-            final SchemaPath schemaPath) {
-        final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(line, containerName, schemaPath);
+    public ContainerSchemaNodeBuilder addContainerNode(final int line, final QName qname, final SchemaPath schemaPath) {
+        final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, containerName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
-    public ListSchemaNodeBuilder addListNode(final int line, final QName listName, final SchemaPath schemaPath) {
-        final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(line, listName, schemaPath);
+    public ListSchemaNodeBuilder addListNode(final int line, final QName qname, final SchemaPath schemaPath) {
+        final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(name, line, qname, schemaPath);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, listName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
-    public LeafSchemaNodeBuilder addLeafNode(final int line, final QName leafName, final SchemaPath schemaPath) {
-        final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(leafName, schemaPath, line);
+    public LeafSchemaNodeBuilder addLeafNode(final int line, final QName qname, final SchemaPath schemaPath) {
+        final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(name, line, qname, schemaPath);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, leafName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
-    public LeafListSchemaNodeBuilder addLeafListNode(final int line, final QName leafListName,
-            final SchemaPath schemaPath) {
-        final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(line, leafListName, schemaPath);
+    public LeafListSchemaNodeBuilder addLeafListNode(final int line, final QName qname, final SchemaPath schemaPath) {
+        final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(name, line, qname, schemaPath);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, leafListName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
     public GroupingBuilder addGrouping(final int line, final QName qname) {
-        final GroupingBuilder builder = new GroupingBuilderImpl(qname, line);
+        final GroupingBuilder builder = new GroupingBuilderImpl(name, line, qname);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
 
+        String groupingName = qname.getLocalName();
         if (parent == null) {
-            for (GroupingBuilder child : addedGroupings) {
-                if (child.getQName().getLocalName().equals(qname.getLocalName())) {
-                    throw new YangParseException(name, line, "Duplicate node found at line " + child.getLine());
+            for (GroupingBuilder addedGrouping : addedGroupings) {
+                if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
+                    throw new YangParseException(name, line, "grouping with same name '" + groupingName
+                            + "' already declared at line " + addedGrouping.getLine());
                 }
             }
             addedGroupings.add(builder);
         } else {
             if (parent instanceof DataNodeContainerBuilder) {
                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
-                for (DataSchemaNodeBuilder child : parentNode.getChildNodeBuilders()) {
-                    if (child.getQName().getLocalName().equals(qname.getLocalName())) {
-                        throw new YangParseException(name, line, "Duplicate node found at line " + child.getLine());
+                for (GroupingBuilder addedGrouping : parentNode.getGroupingBuilders()) {
+                    if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
+                        throw new YangParseException(name, line, "grouping with same name '" + groupingName
+                                + "' already declared at line " + addedGrouping.getLine());
                     }
                 }
                 parentNode.addGrouping(builder);
             } else if (parent instanceof RpcDefinitionBuilder) {
                 RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parent;
                 for (GroupingBuilder child : parentNode.getGroupings()) {
-                    if (child.getQName().getLocalName().equals(qname.getLocalName())) {
-                        throw new YangParseException(name, line, "Duplicate node found at line " + child.getLine());
+                    if (child.getQName().getLocalName().equals(groupingName)) {
+                        throw new YangParseException(name, line, "grouping with same name '" + groupingName
+                                + "' already declared at line " + child.getLine());
                     }
                 }
                 parentNode.addGrouping(builder);
             } else {
-                throw new YangParseException(name, line, "Unresolved parent of grouping " + qname.getLocalName());
+                throw new YangParseException(name, line, "Unresolved parent of grouping " + groupingName);
             }
         }
 
@@ -406,19 +415,20 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     public AugmentationSchemaBuilder addAugment(final int line, final String augmentTargetStr) {
-        final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(line, augmentTargetStr);
+        final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(name, line, augmentTargetStr);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
 
         if (parent == null) {
+            // augment can be declared only under 'module' ...
             addedAugments.add(builder);
         } else {
-            // augment can only be in 'module' or 'uses' statement
+            // ... or 'uses' statement
             if (parent instanceof UsesNodeBuilder) {
                 ((UsesNodeBuilder) parent).addAugment(builder);
             } else {
-                throw new YangParseException(name, line, "Augment can be declared only under module or uses.");
+                throw new YangParseException(name, line, "Augment can be declared only under module or uses statement.");
             }
         }
         allAugments.add(builder);
@@ -433,7 +443,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     public UsesNodeBuilder addUsesNode(final int line, final String groupingPathStr) {
-        final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(line, groupingPathStr);
+        final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(name, line, groupingPathStr);
 
         Builder parent = getActualNode();
         usesBuilder.setParent(parent);
@@ -453,13 +463,11 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         return usesBuilder;
     }
 
-    public void addRefine(final RefineHolder refine, final List<String> parentPath) {
-        final List<String> path = new ArrayList<String>(parentPath);
-
-        if (actualPath.isEmpty()) {
+    public void addRefine(final RefineHolder refine) {
+        final Builder parent = getActualNode();
+        if (parent == null) {
             throw new YangParseException(name, refine.getLine(), "refine can be defined only in uses statement");
         } else {
-            final Builder parent = getActualNode();
             if (parent instanceof UsesNodeBuilder) {
                 ((UsesNodeBuilder) parent).addRefine(refine);
             } else {
@@ -467,8 +475,6 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             }
             refine.setParent(parent);
         }
-
-        path.add(refine.getName());
     }
 
     public RpcDefinitionBuilder addRpc(final int line, final QName qname) {
@@ -477,148 +483,183 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             throw new YangParseException(name, line, "rpc can be defined only in module or submodule");
         }
 
-        final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(line, qname);
+        final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(name, line, qname);
+
+        String rpcName = qname.getLocalName();
         for (RpcDefinitionBuilder rpc : addedRpcs) {
-            if (rpc.getQName().getLocalName().equals(qname.getLocalName())) {
-                throw new YangParseException(name, line, "Duplicate node found at line " + rpc.getLine());
+            if (rpc.getQName().getLocalName().equals(rpcName)) {
+                throw new YangParseException(name, line, "rpc with same name '" + rpcName
+                        + "' already declared at line " + rpc.getLine());
+            }
+        }
+        for (DataSchemaNodeBuilder addedChild : addedChildNodes) {
+            if (addedChild.getQName().getLocalName().equals(rpcName)) {
+                throw new YangParseException(name, line, "Can not add rpc: node with same name '" + rpcName
+                        + "' already declared at line " + addedChild.getLine());
+            }
+        }
+        for (NotificationBuilder addedNotification : addedNotifications) {
+            if (addedNotification.getQName().getLocalName().equals(rpcName)) {
+                throw new YangParseException(name, line, "Can not add rpc: notification with same name '" + rpcName
+                        + "' already declared at line " + addedNotification.getLine());
             }
         }
         addedRpcs.add(rpcBuilder);
         return rpcBuilder;
     }
 
-    public ContainerSchemaNodeBuilder addRpcInput(final SchemaPath schemaPath, final QName inputQName, final int line) {
+    public ContainerSchemaNodeBuilder addRpcInput(final int line, final QName qname, final SchemaPath schemaPath) {
         final Builder parent = getActualNode();
         if (!(parent instanceof RpcDefinitionBuilder)) {
             throw new YangParseException(name, line, "input can be defined only in rpc statement");
         }
         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
 
-        final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(line, inputQName, schemaPath);
+        final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
         inputBuilder.setParent(rpc);
 
         rpc.setInput(inputBuilder);
         return inputBuilder;
     }
 
-    public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName outputQName, final int line) {
+    public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName qname, final int line) {
         final Builder parent = actualPath.getFirst();
         if (!(parent instanceof RpcDefinitionBuilder)) {
             throw new YangParseException(name, line, "output can be defined only in rpc statement");
         }
         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
 
-        final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(line, outputQName, schemaPath);
+        final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
         outputBuilder.setParent(rpc);
 
         rpc.setOutput(outputBuilder);
         return outputBuilder;
     }
 
-    public NotificationBuilder addNotification(final QName notificationName, final List<String> parentPath,
-            final int line) {
+    public NotificationBuilder addNotification(final int line, final QName qname) {
         if (!(actualPath.isEmpty())) {
             throw new YangParseException(name, line, "notification can be defined only in module or submodule");
         }
+
+        String notificationName = qname.getLocalName();
         for (NotificationBuilder nb : addedNotifications) {
-            if (nb.getQName().equals(notificationName)) {
-                throw new YangParseException(name, line, "Duplicate node found at line " + nb.getLine());
+            if (nb.getQName().equals(qname)) {
+                throw new YangParseException(name, line, "notification with same name '" + notificationName
+                        + "' already declared at line " + nb.getLine());
+            }
+        }
+        for (RpcDefinitionBuilder rpc : addedRpcs) {
+            if (rpc.getQName().getLocalName().equals(notificationName)) {
+                throw new YangParseException(name, line, "Can not add notification: rpc with same name '"
+                        + notificationName + "' already declared at line " + rpc.getLine());
+            }
+        }
+        for (DataSchemaNodeBuilder addedChild : addedChildNodes) {
+            if (addedChild.getQName().getLocalName().equals(notificationName)) {
+                throw new YangParseException(name, line, "Can not add notification: node with same name '"
+                        + notificationName + "' already declared at line " + addedChild.getLine());
             }
         }
 
-        final NotificationBuilder builder = new NotificationBuilder(line, notificationName);
+        final NotificationBuilder builder = new NotificationBuilder(name, line, qname);
         addedNotifications.add(builder);
 
         return builder;
     }
 
-    public FeatureBuilder addFeature(final int line, final QName featureName) {
+    public FeatureBuilder addFeature(final int line, final QName qname) {
         Builder parent = getActualNode();
         if (parent != null) {
             throw new YangParseException(name, line, "feature can be defined only in module or submodule");
         }
 
-        final FeatureBuilder builder = new FeatureBuilder(line, featureName);
-        for (FeatureBuilder fb : addedFeatures) {
-            if (fb.getQName().getLocalName().equals(featureName.getLocalName())) {
-                throw new YangParseException(name, line, "Duplicate node found at line " + fb.getLine());
+        final FeatureBuilder builder = new FeatureBuilder(name, line, qname);
+
+        String featureName = qname.getLocalName();
+        for (FeatureBuilder addedFeature : addedFeatures) {
+            if (addedFeature.getQName().getLocalName().equals(featureName)) {
+                throw new YangParseException(name, line, "feature with same name '" + featureName
+                        + "' already declared at line " + addedFeature.getLine());
             }
         }
         addedFeatures.add(builder);
         return builder;
     }
 
-    public ChoiceBuilder addChoice(final int line, final QName choiceName) {
-        final ChoiceBuilder builder = new ChoiceBuilder(line, choiceName);
+    public ChoiceBuilder addChoice(final int line, final QName qname) {
+        final ChoiceBuilder builder = new ChoiceBuilder(name, line, qname);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, choiceName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
-    public ChoiceCaseBuilder addCase(final int line, final QName caseName) {
+    public ChoiceCaseBuilder addCase(final int line, final QName qname) {
         Builder parent = getActualNode();
         if (parent == null) {
             throw new YangParseException(name, line, "'case' parent not found");
         }
 
-        final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(line, caseName);
+        final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(name, line, qname);
         builder.setParent(parent);
 
         if (parent instanceof ChoiceBuilder) {
-            ((ChoiceBuilder) parent).addChildNode(builder);
+            ((ChoiceBuilder) parent).addCase(builder);
         } else if (parent instanceof AugmentationSchemaBuilder) {
             ((AugmentationSchemaBuilder) parent).addChildNode(builder);
         } else {
-            throw new YangParseException(name, line, "Unresolved parent of 'case' " + caseName.getLocalName());
+            throw new YangParseException(name, line, "Unresolved parent of 'case' " + qname.getLocalName());
         }
 
         return builder;
     }
 
-    public AnyXmlBuilder addAnyXml(final int line, final QName anyXmlName, final SchemaPath schemaPath) {
-        final AnyXmlBuilder builder = new AnyXmlBuilder(line, anyXmlName, schemaPath);
+    public AnyXmlBuilder addAnyXml(final int line, final QName qname, final SchemaPath schemaPath) {
+        final AnyXmlBuilder builder = new AnyXmlBuilder(name, line, qname, schemaPath);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
-        addChildToParent(parent, builder, anyXmlName.getLocalName());
+        addChildToParent(parent, builder, qname.getLocalName());
 
         return builder;
     }
 
     @Override
     public void addTypedef(TypeDefinitionBuilder typedefBuilder) {
+        String nodeName = typedefBuilder.getQName().getLocalName();
         for (TypeDefinitionBuilder tdb : addedTypedefs) {
-            if (tdb.getQName().getLocalName().equals(typedefBuilder.getQName().getLocalName())) {
-                throw new YangParseException(name, typedefBuilder.getLine(), "Duplicate node found at line "
-                        + tdb.getLine());
+            if (tdb.getQName().getLocalName().equals(nodeName)) {
+                throw new YangParseException(name, typedefBuilder.getLine(), "typedef with same name '" + nodeName
+                        + "' already declared at line " + tdb.getLine());
             }
         }
         addedTypedefs.add(typedefBuilder);
     }
 
-    public TypeDefinitionBuilderImpl addTypedef(final int line, final QName typeDefName) {
-        final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(typeDefName, line);
+    public TypeDefinitionBuilderImpl addTypedef(final int line, final QName qname) {
+        final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(name, line, qname);
 
         Builder parent = getActualNode();
         builder.setParent(parent);
 
+        String typedefName = qname.getLocalName();
         if (parent == null) {
             for (TypeDefinitionBuilder tdb : addedTypedefs) {
-                if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
-                    throw new YangParseException(name, builder.getLine(), "Duplicate node found at line "
-                            + tdb.getLine());
+                if (tdb.getQName().getLocalName().equals(typedefName)) {
+                    throw new YangParseException(name, line, "typedef with same name '" + typedefName
+                            + "' already declared at line " + tdb.getLine());
                 }
             }
             addedTypedefs.add(builder);
         } else {
             if (parent instanceof DataNodeContainerBuilder) {
                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
-                for (DataSchemaNodeBuilder child : parentNode.getChildNodeBuilders()) {
-                    if (child.getQName().getLocalName().equals(typeDefName.getLocalName())) {
-                        throw new YangParseException(name, line, "Duplicate node found at line " + child.getLine());
+                for (TypeDefinitionBuilder child : parentNode.getTypeDefinitionBuilders()) {
+                    if (child.getQName().getLocalName().equals(typedefName)) {
+                        throw new YangParseException(name, line, "typedef with same name '" + typedefName
+                                + "' already declared at line " + child.getLine());
                     }
                 }
                 parentNode.addTypedef(builder);
@@ -626,13 +667,13 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
                 RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parent;
                 for (TypeDefinitionBuilder tdb : rpcParent.getTypeDefinitions()) {
                     if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
-                        throw new YangParseException(name, builder.getLine(), "Duplicate node found at line "
-                                + tdb.getLine());
+                        throw new YangParseException(name, line, "typedef with same name '" + typedefName
+                                + "' already declared at line " + tdb.getLine());
                     }
                 }
                 rpcParent.addTypedef(builder);
             } else {
-                throw new YangParseException(name, line, "Unresolved parent of typedef " + typeDefName.getLocalName());
+                throw new YangParseException(name, line, "Unresolved parent of typedef " + typedefName);
             }
         }
 
@@ -651,9 +692,9 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     public UnionTypeBuilder addUnionType(final int line, final URI namespace, final Date revision) {
         final Builder parent = getActualNode();
         if (parent == null) {
-            throw new YangParseException(line, "Error while parsing union type");
+            throw new YangParseException(name, line, "Unresolved parent of union type");
         } else {
-            final UnionTypeBuilder union = new UnionTypeBuilder(line);
+            final UnionTypeBuilder union = new UnionTypeBuilder(name, line);
             if (parent instanceof TypeAwareBuilder) {
                 ((TypeAwareBuilder) parent).setTypedef(union);
                 return union;
@@ -664,11 +705,11 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     public void addIdentityrefType(final int line, final SchemaPath schemaPath, final String baseString) {
-        final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(baseString, schemaPath, line);
+        final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(name, line, baseString, schemaPath);
 
         final Builder parent = getActualNode();
         if (parent == null) {
-            throw new YangParseException(line, "Error while parsing identityref type.");
+            throw new YangParseException(name, line, "Unresolved parent of identityref type.");
         } else {
             if (parent instanceof TypeAwareBuilder) {
                 final TypeAwareBuilder typeParent = (TypeAwareBuilder) parent;
@@ -686,7 +727,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             throw new YangParseException(name, line, "deviation can be defined only in module or submodule");
         }
 
-        final DeviationBuilder builder = new DeviationBuilder(line, targetPath);
+        final DeviationBuilder builder = new DeviationBuilder(name, line, targetPath);
         addedDeviations.add(builder);
         return builder;
     }
@@ -696,13 +737,15 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         if (parent != null) {
             throw new YangParseException(name, line, "identity can be defined only in module or submodule");
         }
+        String identityName = qname.getLocalName();
         for (IdentitySchemaNodeBuilder idBuilder : addedIdentities) {
             if (idBuilder.getQName().equals(qname)) {
-                throw new YangParseException(name, line, "Duplicate node found at line " + idBuilder.getLine());
+                throw new YangParseException(name, line, "identity with same name '" + identityName
+                        + "' already declared at line " + idBuilder.getLine());
             }
         }
 
-        final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(line, qname);
+        final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(name, line, qname);
         addedIdentities.add(builder);
         return builder;
     }
@@ -715,7 +758,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
 
     public UnknownSchemaNodeBuilder addUnknownSchemaNode(final int line, final QName qname) {
         final Builder parent = getActualNode();
-        final UnknownSchemaNodeBuilder builder = new UnknownSchemaNodeBuilder(line, qname);
+        final UnknownSchemaNodeBuilder builder = new UnknownSchemaNodeBuilder(name, line, qname);
         builder.setParent(parent);
         allUnknownNodes.add(builder);
 
@@ -1083,7 +1126,16 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         }
     }
 
-    private void addChildToParent(final Builder parent, final DataSchemaNodeBuilder child, final String childLocalName) {
+    /**
+     * Add child to parent. Method checks for duplicates and add given child
+     * node to parent. If node with same name is found, throws exception. If
+     * parent is null, child node will be added directly to module.
+     *
+     * @param parent
+     * @param child
+     * @param childName
+     */
+    private void addChildToParent(final Builder parent, final DataSchemaNodeBuilder child, final String childName) {
         final int line = child.getLine();
         if (parent == null) {
             // if parent == null => node is defined under module
@@ -1092,18 +1144,21 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             // top level of the module or its submodules share the same
             // identifier namespace.
             for (DataSchemaNodeBuilder childNode : addedChildNodes) {
-                if (childNode.getQName().getLocalName().equals(childLocalName)) {
-                    throw new YangParseException(name, line, "Duplicate node found at line " + childNode.getLine());
+                if (childNode.getQName().getLocalName().equals(childName)) {
+                    throw new YangParseException(name, line, "Can not add '" + child
+                            + "': node with same name already declared at line " + childNode.getLine());
                 }
             }
             for (RpcDefinitionBuilder rpc : addedRpcs) {
-                if (rpc.getQName().getLocalName().equals(childLocalName)) {
-                    throw new YangParseException(name, line, "Duplicate node found at line " + rpc.getLine());
+                if (rpc.getQName().getLocalName().equals(childName)) {
+                    throw new YangParseException(name, line, "Can not add '" + child
+                            + "': rpc with same name already declared at line " + rpc.getLine());
                 }
             }
             for (NotificationBuilder notification : addedNotifications) {
-                if (notification.getQName().getLocalName().equals(childLocalName)) {
-                    throw new YangParseException(name, line, "Duplicate node found at line " + notification.getLine());
+                if (notification.getQName().getLocalName().equals(childName)) {
+                    throw new YangParseException(name, line, "Can not add '" + child
+                            + "': notification with same name already declared at line " + notification.getLine());
                 }
             }
             addedChildNodes.add(child);
@@ -1113,22 +1168,23 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             if (parent instanceof DataNodeContainerBuilder) {
                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
                 for (DataSchemaNodeBuilder childNode : parentNode.getChildNodeBuilders()) {
-                    if (childNode.getQName().getLocalName().equals(childLocalName)) {
-                        throw new YangParseException(name, line, "Duplicate node found at line " + childNode.getLine());
+                    if (childNode.getQName().getLocalName().equals(childName)) {
+                        throw new YangParseException(name, line, "Can not add '" + child + "': node with same name '"
+                                + childName + "' already declared at line " + childNode.getLine());
                     }
                 }
                 parentNode.addChildNode(child);
             } else if (parent instanceof ChoiceBuilder) {
                 ChoiceBuilder parentNode = (ChoiceBuilder) parent;
                 for (ChoiceCaseBuilder caseBuilder : parentNode.getCases()) {
-                    if (caseBuilder.getQName().getLocalName().equals(childLocalName)) {
-                        throw new YangParseException(name, line, "Duplicate node found at line "
-                                + caseBuilder.getLine());
+                    if (caseBuilder.getQName().getLocalName().equals(childName)) {
+                        throw new YangParseException(name, line, "Can not add '" + child + "': case with same name '"
+                                + childName + "' already declared at line " + caseBuilder.getLine());
                     }
                 }
-                parentNode.addChildNode(child);
+                parentNode.addCase(child);
             } else {
-                throw new YangParseException(name, line, "Unresolved parent of node '" + childLocalName + "'.");
+                throw new YangParseException(name, line, "Unresolved parent of node '" + childName + "'.");
             }
         }
     }
index 14b701fe9eb9dd412a76665bdad0d471e45df1db..eab1cffcebadadc80b09cae88ffa7a1edb11899a 100644 (file)
@@ -49,8 +49,8 @@ public final class NotificationBuilder extends AbstractDataNodeContainerBuilder
     private Set<AugmentationSchema> augmentations;
     private final Set<AugmentationSchemaBuilder> addedAugmentations = new HashSet<AugmentationSchemaBuilder>();
 
-    NotificationBuilder(final int line, final QName qname) {
-        super(line, qname);
+    NotificationBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new NotificationDefinitionImpl(qname);
     }
 
index 65b15c583b672b30acc0be6531b91209d3202458..53190d0bb6df4ec6b83b57623404674c59a34060 100644 (file)
@@ -35,8 +35,8 @@ public final class RpcDefinitionBuilder extends AbstractSchemaNodeBuilder {
     private final Set<TypeDefinitionBuilder> addedTypedefs = new HashSet<TypeDefinitionBuilder>();
     private final Set<GroupingBuilder> addedGroupings = new HashSet<GroupingBuilder>();
 
-    RpcDefinitionBuilder(final int line, final QName qname) {
-        super(line, qname);
+    RpcDefinitionBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         this.instance = new RpcDefinitionImpl(qname);
     }
 
index 7ff78477637ef2757fc75c28ccd59167d7c5baaa..5f2ca1c028388c2273c13aa5d73ef5dd8dac2949 100644 (file)
@@ -40,12 +40,12 @@ public final class TypeDefinitionBuilderImpl extends AbstractTypeAwareBuilder im
     private Object defaultValue;
     private boolean addedByUses;
 
-    public TypeDefinitionBuilderImpl(final QName qname, final int line) {
-        super(line, qname);
+    public TypeDefinitionBuilderImpl(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
     }
 
     public TypeDefinitionBuilderImpl(TypeDefinitionBuilder tdb) {
-        super(tdb.getLine(), tdb.getQName());
+        super(tdb.getModuleName(), tdb.getLine(), tdb.getQName());
         schemaPath = tdb.getPath();
 
         type = tdb.getType();
index fac500194407563d0c1cf623f415c4ac0b6a5ec8..6c57c25b988949587a68a878b9357fbd290f2a73 100644 (file)
@@ -39,13 +39,12 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     private SchemaPath path;
 
-    public UnionTypeBuilder(final int line) {
-        super(line, null);
+    public UnionTypeBuilder(final String moduleName, final int line) {
+        super(moduleName, line, null);
         types = new ArrayList<TypeDefinition<?>>();
         typedefs = new ArrayList<TypeDefinitionBuilder>();
     }
 
-
     public List<TypeDefinition<?>> getTypes() {
         return types;
     }
@@ -93,17 +92,17 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setDescription(final String description) {
-        throw new YangParseException(line, "Can not set description to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set description to " + NAME);
     }
 
     @Override
     public void setReference(final String reference) {
-        throw new YangParseException(line, "Can not set reference to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set reference to " + NAME);
     }
 
     @Override
     public void setStatus(final Status status) {
-        throw new YangParseException(line, "Can not set status to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set status to " + NAME);
     }
 
     @Override
@@ -113,7 +112,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setAddedByUses(final boolean addedByUses) {
-        throw new YangParseException(line, "Union type can not be added by uses.");
+        throw new YangParseException(moduleName, line, "Union type can not be added by uses.");
     }
 
     @Override
@@ -153,7 +152,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setRanges(List<RangeConstraint> ranges) {
-        throw new YangParseException(line, "Can not set ranges to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set ranges to " + NAME);
     }
 
     @Override
@@ -163,7 +162,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setLengths(List<LengthConstraint> lengths) {
-        throw new YangParseException(line, "Can not set lengths to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set lengths to " + NAME);
     }
 
     @Override
@@ -173,7 +172,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setPatterns(List<PatternConstraint> patterns) {
-        throw new YangParseException(line, "Can not set patterns to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set patterns to " + NAME);
     }
 
     @Override
@@ -183,7 +182,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setFractionDigits(Integer fractionDigits) {
-        throw new YangParseException(line, "Can not set fraction digits to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set fraction digits to " + NAME);
     }
 
     @Override
@@ -198,7 +197,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setDefaultValue(Object defaultValue) {
-        throw new YangParseException(line, "Can not set default value to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set default value to " + NAME);
     }
 
     @Override
@@ -208,7 +207,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
 
     @Override
     public void setUnits(String units) {
-        throw new YangParseException(line, "Can not set units to " + NAME);
+        throw new YangParseException(moduleName, line, "Can not set units to " + NAME);
     }
 
     @Override
index 267696bdae8383fbd911d3fd6488f372cc3f0a9b..e7b344b6fdce0a7da29563ce0d64563b2231f865 100644 (file)
@@ -25,13 +25,13 @@ public final class UnknownSchemaNodeBuilder extends AbstractSchemaNodeBuilder {
     private QName nodeType;
     private String nodeParameter;
 
-    public UnknownSchemaNodeBuilder(final int line, final QName qname) {
-        super(line, qname);
+    public UnknownSchemaNodeBuilder(final String moduleName, final int line, final QName qname) {
+        super(moduleName, line, qname);
         instance = new UnknownSchemaNodeImpl(qname);
     }
 
     public UnknownSchemaNodeBuilder(UnknownSchemaNodeBuilder b) {
-        super(b.getLine(), b.getQName());
+        super(b.getModuleName(), b.getLine(), b.getQName());
         instance = new UnknownSchemaNodeImpl(qname);
         schemaPath = b.getPath();
         description = b.getDescription();
index 3b1eb33d3940b86187848d9cd2cd08397ecae963..ee07e8be4603ac99d14f68f2c0fbaf33abc97db6 100644 (file)
@@ -20,6 +20,7 @@ import org.opendaylight.controller.yang.model.api.SchemaNode;
 import org.opendaylight.controller.yang.model.api.SchemaPath;\r
 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;\r
 import org.opendaylight.controller.yang.model.api.UsesNode;\r
+import org.opendaylight.controller.yang.parser.builder.api.AbstractBuilder;\r
 import org.opendaylight.controller.yang.parser.builder.api.AugmentationSchemaBuilder;\r
 import org.opendaylight.controller.yang.parser.builder.api.Builder;\r
 import org.opendaylight.controller.yang.parser.builder.api.DataNodeContainerBuilder;\r
@@ -28,10 +29,9 @@ import org.opendaylight.controller.yang.parser.builder.api.UsesNodeBuilder;
 import org.opendaylight.controller.yang.parser.util.RefineHolder;\r
 import org.opendaylight.controller.yang.parser.util.YangParseException;\r
 \r
-public final class UsesNodeBuilderImpl implements UsesNodeBuilder {\r
+public final class UsesNodeBuilderImpl extends AbstractBuilder implements UsesNodeBuilder {\r
     private boolean isBuilt;\r
     private UsesNodeImpl instance;\r
-    private final int line;\r
     private DataNodeContainerBuilder parent;\r
     private final String groupingName;\r
     private SchemaPath groupingPath;\r
@@ -40,16 +40,15 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
     private final Set<AugmentationSchemaBuilder> addedAugments = new HashSet<AugmentationSchemaBuilder>();\r
     private final List<SchemaNodeBuilder> refineBuilders = new ArrayList<SchemaNodeBuilder>();\r
     private final List<RefineHolder> refines = new ArrayList<RefineHolder>();\r
-    private final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();\r
 \r
-    public UsesNodeBuilderImpl(final int line, final String groupingName) {\r
+    public UsesNodeBuilderImpl(final String moduleName, final int line, final String groupingName) {\r
+        super(moduleName, line);\r
         this.groupingName = groupingName;\r
-        this.line = line;\r
     }\r
 \r
     public UsesNodeBuilderImpl(UsesNodeBuilder b) {\r
+        super(b.getModuleName(), b.getLine());\r
         groupingName = b.getGroupingName();\r
-        line = b.getLine();\r
         parent = b.getParent();\r
         groupingPath = b.getGroupingPath();\r
         augmenting = b.isAugmenting();\r
@@ -93,11 +92,6 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
         return instance;\r
     }\r
 \r
-    @Override\r
-    public int getLine() {\r
-        return line;\r
-    }\r
-\r
     @Override\r
     public DataNodeContainerBuilder getParent() {\r
         return parent;\r
@@ -106,7 +100,7 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
     @Override\r
     public void setParent(Builder parent) {\r
         if (!(parent instanceof DataNodeContainerBuilder)) {\r
-            throw new YangParseException(line, "Unresolved parent of uses '" + groupingName + "'.");\r
+            throw new YangParseException(moduleName, line, "Unresolved parent of uses '" + groupingName + "'.");\r
         }\r
         this.parent = (DataNodeContainerBuilder) parent;\r
     }\r
@@ -176,16 +170,6 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
         refines.add(refine);\r
     }\r
 \r
-    @Override\r
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {\r
-        return addedUnknownNodes;\r
-    }\r
-\r
-    @Override\r
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {\r
-        addedUnknownNodes.add(unknownNode);\r
-    }\r
-\r
     @Override\r
     public int hashCode() {\r
         final int prime = 31;\r
index 7d64b944219d122ad84d157cd383eb054bb02b10..0c1f5e27dddfe036a4b6fe6b562198508fecf67c 100644 (file)
@@ -921,7 +921,7 @@ public final class YangParserImpl implements YangModelParser {
                 usesNode.setGroupingPath(targetGrouping.getPath());
                 for (RefineHolder refine : usesNode.getRefines()) {
                     final SchemaNodeBuilder nodeToRefine = RefineUtils.getRefineNodeFromGroupingDefinition(
-                            targetGrouping, refine, module.getName());
+                            targetGrouping, refine);
                     if (nodeToRefine instanceof GroupingMember) {
                         ((GroupingMember) nodeToRefine).setAddedByUses(true);
                     }
@@ -1053,7 +1053,8 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     /**
-     * Add nodes defined in target grouping to current context.
+     * Add nodes defined in target grouping to current context. Refinement has
+     * to be already performed.
      *
      * @param usesNode
      * @param targetGrouping
@@ -1088,7 +1089,7 @@ public final class YangParserImpl implements YangModelParser {
                 }
 
                 if (newChild == null) {
-                    throw new YangParseException(usesNode.getLine(),
+                    throw new YangParseException(usesNode.getModuleName(), usesNode.getLine(),
                             "Unknown member of target grouping while resolving uses node.");
                 }
 
@@ -1127,6 +1128,7 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     private void processUsesNode(final UsesNodeBuilder usesNode, final GroupingDefinition targetGrouping) {
+        final String moduleName = usesNode.getModuleName();
         final int line = usesNode.getLine();
         List<SchemaNodeBuilder> refineNodes = usesNode.getRefineNodes();
         DataNodeContainerBuilder parent = usesNode.getParent();
@@ -1143,21 +1145,21 @@ public final class YangParserImpl implements YangModelParser {
 
                 DataSchemaNodeBuilder newChild = null;
                 if (child instanceof AnyXmlSchemaNode) {
-                    newChild = createAnyXml((AnyXmlSchemaNode) child, line);
+                    newChild = createAnyXml((AnyXmlSchemaNode) child, moduleName, line);
                 } else if (child instanceof ChoiceNode) {
-                    newChild = createChoice((ChoiceNode) child, line);
+                    newChild = createChoice((ChoiceNode) child, moduleName, line);
                 } else if (child instanceof ContainerSchemaNode) {
-                    newChild = createContainer((ContainerSchemaNode) child, line);
+                    newChild = createContainer((ContainerSchemaNode) child, moduleName, line);
                 } else if (child instanceof LeafListSchemaNode) {
-                    newChild = createLeafList((LeafListSchemaNode) child, line);
+                    newChild = createLeafList((LeafListSchemaNode) child, moduleName, line);
                 } else if (child instanceof LeafSchemaNode) {
-                    newChild = createLeafBuilder((LeafSchemaNode) child, line);
+                    newChild = createLeafBuilder((LeafSchemaNode) child, moduleName, line);
                 } else if (child instanceof ListSchemaNode) {
-                    newChild = createList((ListSchemaNode) child, line);
+                    newChild = createList((ListSchemaNode) child, moduleName, line);
                 }
 
                 if (newChild == null) {
-                    throw new YangParseException(usesNode.getLine(),
+                    throw new YangParseException(moduleName, line,
                             "Unknown member of target grouping while resolving uses node.");
                 }
 
@@ -1169,13 +1171,13 @@ public final class YangParserImpl implements YangModelParser {
             }
         }
         for (GroupingDefinition g : targetGrouping.getGroupings()) {
-            GroupingBuilder newGrouping = createGrouping(g, line);
+            GroupingBuilder newGrouping = createGrouping(g, moduleName, line);
             newGrouping.setAddedByUses(true);
             newGrouping.setPath(createSchemaPath(parentPath, newGrouping.getQName().getLocalName()));
             parent.addGrouping(newGrouping);
         }
         for (TypeDefinition<?> td : targetGrouping.getTypeDefinitions()) {
-            TypeDefinitionBuilder newType = createTypedef((ExtendedType) td, line);
+            TypeDefinitionBuilder newType = createTypedef((ExtendedType) td, moduleName, line);
             newType.setAddedByUses(true);
             newType.setPath(createSchemaPath(parentPath, newType.getQName().getLocalName()));
             parent.addTypedef(newType);
@@ -1189,7 +1191,7 @@ public final class YangParserImpl implements YangModelParser {
             }
         }
         for (UnknownSchemaNode un : targetGrouping.getUnknownSchemaNodes()) {
-            UnknownSchemaNodeBuilder newNode = createUnknownSchemaNode(un, line);
+            UnknownSchemaNodeBuilder newNode = createUnknownSchemaNode(un, moduleName, line);
             newNode.setAddedByUses(true);
             newNode.setPath(createSchemaPath(parentPath, un.getQName().getLocalName()));
             parent.addUnknownNodeBuilder(newNode);
index 155deced668e9bb19462c64eab3c752fd7ee1acb..77ac8a56201709baaa3f163476467d11412c1c97 100644 (file)
@@ -373,13 +373,13 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                     SchemaPath path = createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix, typeName);
                     moduleBuilder.addIdentityrefType(line, path, getIdentityrefBase(typeBody));
                 } else {
-                    type = parseTypeWithBody(moduleName, typeName, typeBody, actualPath, namespace, revision,
-                            yangModelPrefix, moduleBuilder.getActualNode());
+                    type = parseTypeWithBody(typeName, typeBody, actualPath, namespace, revision, yangModelPrefix,
+                            moduleBuilder.getActualNode());
                     moduleBuilder.setType(type);
                 }
             }
         } else {
-            type = parseUnknownTypeWithBody(moduleName, typeQName, typeBody, actualPath, namespace, revision, yangModelPrefix,
+            type = parseUnknownTypeWithBody(typeQName, typeBody, actualPath, namespace, revision, yangModelPrefix,
                     moduleBuilder.getActualNode());
             // add parent node of this type statement to dirty nodes
             moduleBuilder.markActualNodeDirty();
@@ -528,8 +528,8 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         final String refineString = stringFromNode(ctx);
         enterLog("refine", refineString, ctx.getStart().getLine());
 
-        RefineHolder refine = parseRefine(ctx);
-        moduleBuilder.addRefine(refine, actualPath);
+        RefineHolder refine = parseRefine(ctx, moduleName);
+        moduleBuilder.addRefine(refine);
         moduleBuilder.enterNode(refine);
         actualPath.push(refineString);
     }
@@ -699,7 +699,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         enterLog("notification", notificationName, line);
 
         QName notificationQName = new QName(namespace, revision, yangModelPrefix, notificationName);
-        NotificationBuilder builder = moduleBuilder.addNotification(notificationQName, actualPath, line);
+        NotificationBuilder builder = moduleBuilder.addNotification(line, notificationQName);
         moduleBuilder.enterNode(builder);
         actualPath.push(notificationName);
 
@@ -787,7 +787,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         QName rpcQName = new QName(namespace, revision, yangModelPrefix, input);
         SchemaPath path = createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix, input);
 
-        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcInput(path, rpcQName, line);
+        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcInput(line, rpcQName, path);
         moduleBuilder.enterNode(builder);
         actualPath.push(input);
 
index 5f291d74a3d0325e9d00994e635bbe4418e6e105..d2ca3a7695b57d9a3298d1c651fc83e01b0ef113 100644 (file)
@@ -326,13 +326,14 @@ public final class ParserListenerUtils {
      *            type body context to parse
      * @param path
      *            actual position in YANG model
+     * @param moduleName current module name
      * @param namespace
      * @param revision
      * @param prefix
      * @return List of EnumPair object parsed from given context
      */
     private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
-            final List<String> path, final URI namespace, final Date revision, final String prefix) {
+            final List<String> path, final String moduleName, final URI namespace, final Date revision, final String prefix) {
         List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<EnumTypeDefinition.EnumPair>();
 
         for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -342,7 +343,7 @@ public final class ParserListenerUtils {
                 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
                     ParseTree enumChild = enumSpecChild.getChild(j);
                     if (enumChild instanceof Enum_stmtContext) {
-                        EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, namespace,
+                        EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName, namespace,
                                 revision, prefix);
                         if (enumPair.getValue() > highestValue) {
                             highestValue = enumPair.getValue();
@@ -364,13 +365,16 @@ public final class ParserListenerUtils {
      *            current highest value in enumeration
      * @param path
      *            actual position in YANG model
+     * @param moduleName
+     *            current module name
      * @param namespace
      * @param revision
      * @param prefix
      * @return EnumPair object parsed from given context
      */
     private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
-            final List<String> path, final URI namespace, final Date revision, final String prefix) {
+            final List<String> path, final String moduleName, final URI namespace, final Date revision,
+            final String prefix) {
         final String name = stringFromNode(ctx);
         final QName qname = new QName(namespace, revision, prefix, name);
         Integer value = null;
@@ -400,7 +404,7 @@ public final class ParserListenerUtils {
             value = highestValue + 1;
         }
         if (value < -2147483648 || value > 2147483647) {
-            throw new YangParseException(ctx.getStart().getLine(), "Error on enum '" + name
+            throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
                     + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
         }
 
@@ -543,7 +547,7 @@ public final class ParserListenerUtils {
      *            type body context to parse
      * @return List of RangeConstraint created from this context
      */
-    private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx) {
+    private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
         List<RangeConstraint> rangeConstraints = Collections.emptyList();
         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree numRestrChild = ctx.getChild(i);
@@ -551,7 +555,7 @@ public final class ParserListenerUtils {
                 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
                     ParseTree rangeChild = numRestrChild.getChild(j);
                     if (rangeChild instanceof Range_stmtContext) {
-                        rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild);
+                        rangeConstraints = parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
                         break outer;
                     }
                 }
@@ -567,7 +571,7 @@ public final class ParserListenerUtils {
      *            range context to parse
      * @return List of RangeConstraints parsed from this context
      */
-    private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx) {
+    private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
         final int line = ctx.getStart().getLine();
         List<RangeConstraint> rangeConstraints = new ArrayList<RangeConstraint>();
         String description = null;
@@ -590,10 +594,10 @@ public final class ParserListenerUtils {
             Number min;
             Number max;
             if (splittedRangeDef.length == 1) {
-                min = max = parseNumberConstraintValue(splittedRangeDef[0], line);
+                min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
             } else {
-                min = parseNumberConstraintValue(splittedRangeDef[0], line);
-                max = parseNumberConstraintValue(splittedRangeDef[1], line);
+                min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
+                max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
             }
             RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
             rangeConstraints.add(range);
@@ -609,7 +613,7 @@ public final class ParserListenerUtils {
      *            type body context to parse
      * @return List of LengthConstraint created from this context
      */
-    private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx) {
+    private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
         List<LengthConstraint> lengthConstraints = Collections.emptyList();
         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree stringRestrChild = ctx.getChild(i);
@@ -617,7 +621,7 @@ public final class ParserListenerUtils {
                 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
                     ParseTree lengthChild = stringRestrChild.getChild(j);
                     if (lengthChild instanceof Length_stmtContext) {
-                        lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild);
+                        lengthConstraints = parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
                         break outer;
                     }
                 }
@@ -633,7 +637,7 @@ public final class ParserListenerUtils {
      *            length context to parse
      * @return List of LengthConstraints parsed from this context
      */
-    private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx) {
+    private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
         final int line = ctx.getStart().getLine();
         List<LengthConstraint> lengthConstraints = new ArrayList<LengthConstraint>();
         String description = null;
@@ -656,10 +660,10 @@ public final class ParserListenerUtils {
             Number min;
             Number max;
             if (splittedRangeDef.length == 1) {
-                min = max = parseNumberConstraintValue(splittedRangeDef[0], line);
+                min = max = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
             } else {
-                min = parseNumberConstraintValue(splittedRangeDef[0], line);
-                max = parseNumberConstraintValue(splittedRangeDef[1], line);
+                min = parseNumberConstraintValue(splittedRangeDef[0], moduleName, line);
+                max = parseNumberConstraintValue(splittedRangeDef[1], moduleName, line);
             }
             LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
             lengthConstraints.add(range);
@@ -674,7 +678,7 @@ public final class ParserListenerUtils {
      * @return wrapper object of primitive java type or UnknownBoundaryNumber if
      *         type is one of special YANG values 'min' or 'max'
      */
-    private static Number parseNumberConstraintValue(final String value, final int line) {
+    private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
         Number result = null;
         if ("min".equals(value) || "max".equals(value)) {
             result = new UnknownBoundaryNumber(value);
@@ -682,7 +686,7 @@ public final class ParserListenerUtils {
             try {
                 result = Long.valueOf(value);
             } catch (NumberFormatException e) {
-                throw new YangParseException(line, "Unable to parse range value '" + value + "'.", e);
+                throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
             }
         }
         return result;
@@ -812,13 +816,14 @@ public final class ParserListenerUtils {
      *            type body context to parse
      * @param actualPath
      *            current position in YANG model
+     * @param moduleName current module name
      * @param namespace
      * @param revision
      * @param prefix
      * @return List of Bit objects created from this context
      */
     private static List<BitsTypeDefinition.Bit> getBits(Type_body_stmtsContext ctx, List<String> actualPath,
-            URI namespace, Date revision, String prefix) {
+            String moduleName, URI namespace, Date revision, String prefix) {
         final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
         for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree bitsSpecChild = ctx.getChild(j);
@@ -827,7 +832,7 @@ public final class ParserListenerUtils {
                 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
                     ParseTree bitChild = bitsSpecChild.getChild(k);
                     if (bitChild instanceof Bit_stmtContext) {
-                        Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, namespace,
+                        Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName, namespace,
                                 revision, prefix);
                         if (bit.getPosition() > highestPosition) {
                             highestPosition = bit.getPosition();
@@ -849,13 +854,14 @@ public final class ParserListenerUtils {
      *            current highest position in bits type
      * @param actualPath
      *            current position in YANG model
+     * @param moduleName current module name
      * @param namespace
      * @param revision
      * @param prefix
      * @return Bit object parsed from this context
      */
     private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, long highestPosition,
-            List<String> actualPath, final URI namespace, final Date revision, final String prefix) {
+            List<String> actualPath, final String moduleName, final URI namespace, final Date revision, final String prefix) {
         String name = stringFromNode(ctx);
         final QName qname = new QName(namespace, revision, prefix, name);
         Long position = null;
@@ -888,7 +894,7 @@ public final class ParserListenerUtils {
             position = highestPosition + 1;
         }
         if (position < 0 || position > 4294967295L) {
-            throw new YangParseException(ctx.getStart().getLine(), "Error on bit '" + name
+            throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
                     + "': the position value MUST be in the range 0 to 4294967295");
         }
 
@@ -946,7 +952,7 @@ public final class ParserListenerUtils {
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree child = ctx.getChild(i);
             if (child instanceof Config_stmtContext) {
-                config = parseConfig((Config_stmtContext) child);
+                config = parseConfig((Config_stmtContext) child, moduleName);
                 break;
             }
         }
@@ -994,10 +1000,11 @@ public final class ParserListenerUtils {
      * Parse config statement.
      *
      * @param ctx
-     *            config context to parse.
+     *            config context to parse
+     * @param moduleName current module name
      * @return true if given context contains string 'true', false otherwise
      */
-    private static Boolean parseConfig(final Config_stmtContext ctx) {
+    private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
         Boolean result = null;
         if (ctx != null) {
             for (int i = 0; i < ctx.getChildCount(); ++i) {
@@ -1011,7 +1018,7 @@ public final class ParserListenerUtils {
                         result = false;
                         break;
                     } else {
-                        throw new YangParseException(ctx.getStart().getLine(),
+                        throw new YangParseException(moduleName, ctx.getStart().getLine(),
                                 "Failed to parse 'config' statement value: '" + value + "'.");
                     }
                 }
@@ -1023,8 +1030,6 @@ public final class ParserListenerUtils {
     /**
      * Parse type body and create UnknownType definition.
      *
-     * @param moduleName
-     *            name of current module
      * @param typedefQName
      *            qname of current type
      * @param ctx
@@ -1036,16 +1041,17 @@ public final class ParserListenerUtils {
      * @param parent
      * @return UnknownType object with constraints from parsed type body
      */
-    public static TypeDefinition<?> parseUnknownTypeWithBody(final String moduleName, final QName typedefQName,
+    public static TypeDefinition<?> parseUnknownTypeWithBody(final QName typedefQName,
             final Type_body_stmtsContext ctx, final List<String> actualPath, final URI namespace, final Date revision,
             final String prefix, final Builder parent) {
+        String moduleName = parent.getModuleName();
         String typeName = typedefQName.getLocalName();
 
         UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
 
         if (ctx != null) {
-            List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
-            List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
+            List<RangeConstraint> rangeStatements = getRangeConstraints(ctx, moduleName);
+            List<LengthConstraint> lengthStatements = getLengthConstraints(ctx, moduleName);
             List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
             Integer fractionDigits = getFractionDigits(ctx, moduleName);
 
@@ -1080,8 +1086,6 @@ public final class ParserListenerUtils {
     /**
      * Create TypeDefinition object based on given type name and type body.
      *
-     * @param moduleName
-     *            current module name
      * @param typeName
      *            name of type
      * @param typeBody
@@ -1098,16 +1102,17 @@ public final class ParserListenerUtils {
      *            parent builder
      * @return TypeDefinition object based on parsed values.
      */
-    public static TypeDefinition<?> parseTypeWithBody(final String moduleName, final String typeName,
+    public static TypeDefinition<?> parseTypeWithBody(final String typeName,
             final Type_body_stmtsContext typeBody, final List<String> actualPath, final URI namespace,
             final Date revision, final String prefix, final Builder parent) {
+        final String moduleName = parent.getModuleName();
         final int line = typeBody.getStart().getLine();
         TypeDefinition<?> baseType = null;
 
         Integer fractionDigits = getFractionDigits(typeBody, moduleName);
-        List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
+        List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
-        List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
+        List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
 
         TypeConstraints constraints = new TypeConstraints(moduleName, line);
         constraints.addFractionDigits(fractionDigits);
@@ -1159,7 +1164,7 @@ public final class ParserListenerUtils {
             constraints.addRanges(uintType.getRangeStatements());
             baseType = uintType;
         } else if ("enumeration".equals(typeName)) {
-            List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, namespace,
+            List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName, namespace,
                     revision, prefix);
             return new EnumerationType(baseTypePathFinal, enumConstants);
         } else if ("string".equals(typeName)) {
@@ -1167,7 +1172,7 @@ public final class ParserListenerUtils {
             constraints.addLengths(stringType.getLengthStatements());
             baseType = stringType;
         } else if ("bits".equals(typeName)) {
-            return new BitsType(baseTypePathFinal, getBits(typeBody, actualPath, namespace, revision, prefix));
+            return new BitsType(baseTypePathFinal, getBits(typeBody, actualPath, moduleName, namespace, revision, prefix));
         } else if ("leafref".equals(typeName)) {
             final String path = parseLeafrefPath(typeBody);
             final boolean absolute = path.startsWith("/");
@@ -1382,10 +1387,10 @@ public final class ParserListenerUtils {
         for (int i = 0; i < ctx.getChildCount(); ++i) {
             final ParseTree childNode = ctx.getChild(i);
             if (childNode instanceof Max_elements_stmtContext) {
-                Integer max = parseMaxElements((Max_elements_stmtContext) childNode);
+                Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
                 constraints.setMaxElements(max);
             } else if (childNode instanceof Min_elements_stmtContext) {
-                Integer min = parseMinElements((Min_elements_stmtContext) childNode);
+                Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
                 constraints.setMinElements(min);
             } else if (childNode instanceof Must_stmtContext) {
                 MustDefinition must = parseMust((Must_stmtContext) childNode);
@@ -1404,7 +1409,7 @@ public final class ParserListenerUtils {
         }
     }
 
-    private static Integer parseMinElements(Min_elements_stmtContext ctx) {
+    private static Integer parseMinElements(Min_elements_stmtContext ctx, String moduleName) {
         Integer result = null;
         try {
             for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -1418,11 +1423,11 @@ public final class ParserListenerUtils {
             }
             return result;
         } catch (Exception e) {
-            throw new YangParseException(ctx.getStart().getLine(), "Failed to parse min-elements.", e);
+            throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
         }
     }
 
-    private static Integer parseMaxElements(Max_elements_stmtContext ctx) {
+    private static Integer parseMaxElements(Max_elements_stmtContext ctx, String moduleName) {
         Integer result = null;
         try {
             for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -1436,7 +1441,7 @@ public final class ParserListenerUtils {
             }
             return result;
         } catch (Exception e) {
-            throw new YangParseException(ctx.getStart().getLine(), "Failed to parse max-elements.", e);
+            throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
         }
     }
 
@@ -1506,9 +1511,9 @@ public final class ParserListenerUtils {
      *            refine statement
      * @return RefineHolder object representing this refine statement
      */
-    public static RefineHolder parseRefine(Refine_stmtContext refineCtx) {
+    public static RefineHolder parseRefine(Refine_stmtContext refineCtx, String moduleName) {
         final String refineTarget = stringFromNode(refineCtx);
-        final RefineHolder refine = new RefineHolder(refineCtx.getStart().getLine(), refineTarget);
+        final RefineHolder refine = new RefineHolder(moduleName, refineCtx.getStart().getLine(), refineTarget);
         for (int i = 0; i < refineCtx.getChildCount(); i++) {
             ParseTree refinePom = refineCtx.getChild(i);
             if (refinePom instanceof Refine_pomContext) {
@@ -1545,7 +1550,7 @@ public final class ParserListenerUtils {
                 String reference = stringFromNode(refineArg);
                 refine.setReference(reference);
             } else if (refineArg instanceof Config_stmtContext) {
-                Boolean config = parseConfig((Config_stmtContext) refineArg);
+                Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
                 refine.setConfiguration(config);
             }
         }
@@ -1594,10 +1599,10 @@ public final class ParserListenerUtils {
                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
                 refine.setMust(must);
             } else if (refineArg instanceof Max_elements_stmtContext) {
-                Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
+                Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
                 refine.setMaxElements(max);
             } else if (refineArg instanceof Min_elements_stmtContext) {
-                Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
+                Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
                 refine.setMinElements(min);
             }
         }
@@ -1611,10 +1616,10 @@ public final class ParserListenerUtils {
                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
                 refine.setMust(must);
             } else if (refineArg instanceof Max_elements_stmtContext) {
-                Integer max = parseMaxElements((Max_elements_stmtContext) refineArg);
+                Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
                 refine.setMaxElements(max);
             } else if (refineArg instanceof Min_elements_stmtContext) {
-                Integer min = parseMinElements((Min_elements_stmtContext) refineArg);
+                Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
                 refine.setMinElements(min);
             }
         }
index 587c8bed4ef19272ce420e92d0ffca1b6aef0a1f..25232796cc9c3ba15307cf496b7ccc10ca6157f2 100644 (file)
@@ -482,7 +482,7 @@ public final class ParserUtils {
                 }
             }
             correctAugmentChildPath(builder, target.getPath());
-            target.addChildNode(builder);
+            target.addCase(builder);
         }
     }
 
@@ -750,8 +750,9 @@ public final class ParserUtils {
      *            line in module
      * @return builder object from leaf
      */
-    public static LeafSchemaNodeBuilder createLeafBuilder(LeafSchemaNode leaf, int line) {
-        final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(leaf.getQName(), leaf.getPath(), line);
+    public static LeafSchemaNodeBuilder createLeafBuilder(LeafSchemaNode leaf, String moduleName, int line) {
+        final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(moduleName, line, leaf.getQName(),
+                leaf.getPath());
         convertDataSchemaNode(leaf, builder);
         builder.setConfiguration(leaf.isConfiguration());
         final TypeDefinition<?> type = leaf.getType();
@@ -763,9 +764,9 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static ContainerSchemaNodeBuilder createContainer(ContainerSchemaNode container, int line) {
-        final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(line, container.getQName(),
-                container.getPath());
+    public static ContainerSchemaNodeBuilder createContainer(ContainerSchemaNode container, String moduleName, int line) {
+        final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(moduleName, line,
+                container.getQName(), container.getPath());
         convertDataSchemaNode(container, builder);
         builder.setConfiguration(container.isConfiguration());
         builder.setUnknownNodes(container.getUnknownSchemaNodes());
@@ -778,8 +779,8 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static ListSchemaNodeBuilder createList(ListSchemaNode list, int line) {
-        ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(line, list.getQName(), list.getPath());
+    public static ListSchemaNodeBuilder createList(ListSchemaNode list, String moduleName, int line) {
+        ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(moduleName, line, list.getQName(), list.getPath());
         convertDataSchemaNode(list, builder);
         builder.setConfiguration(list.isConfiguration());
         builder.setUnknownNodes(list.getUnknownSchemaNodes());
@@ -792,8 +793,8 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static LeafListSchemaNodeBuilder createLeafList(LeafListSchemaNode leafList, int line) {
-        final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(line, leafList.getQName(),
+    public static LeafListSchemaNodeBuilder createLeafList(LeafListSchemaNode leafList, String moduleName, int line) {
+        final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(moduleName, line, leafList.getQName(),
                 leafList.getPath());
         convertDataSchemaNode(leafList, builder);
         builder.setConfiguration(leafList.isConfiguration());
@@ -803,8 +804,8 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static ChoiceBuilder createChoice(ChoiceNode choice, int line) {
-        final ChoiceBuilder builder = new ChoiceBuilder(line, choice.getQName());
+    public static ChoiceBuilder createChoice(ChoiceNode choice, String moduleName, int line) {
+        final ChoiceBuilder builder = new ChoiceBuilder(moduleName, line, choice.getQName());
         convertDataSchemaNode(choice, builder);
         builder.setConfiguration(choice.isConfiguration());
         builder.setCases(choice.getCases());
@@ -813,16 +814,16 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static AnyXmlBuilder createAnyXml(AnyXmlSchemaNode anyxml, int line) {
-        final AnyXmlBuilder builder = new AnyXmlBuilder(line, anyxml.getQName(), anyxml.getPath());
+    public static AnyXmlBuilder createAnyXml(AnyXmlSchemaNode anyxml, String moduleName, int line) {
+        final AnyXmlBuilder builder = new AnyXmlBuilder(moduleName, line, anyxml.getQName(), anyxml.getPath());
         convertDataSchemaNode(anyxml, builder);
         builder.setConfiguration(anyxml.isConfiguration());
         builder.setUnknownNodes(anyxml.getUnknownSchemaNodes());
         return builder;
     }
 
-    public static GroupingBuilder createGrouping(GroupingDefinition grouping, int line) {
-        final GroupingBuilderImpl builder = new GroupingBuilderImpl(grouping.getQName(), line);
+    public static GroupingBuilder createGrouping(GroupingDefinition grouping, String moduleName, int line) {
+        final GroupingBuilderImpl builder = new GroupingBuilderImpl(moduleName, line, grouping.getQName());
         builder.setPath(grouping.getPath());
         builder.setChildNodes(grouping.getChildNodes());
         builder.setGroupings(grouping.getGroupings());
@@ -835,8 +836,8 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static TypeDefinitionBuilder createTypedef(ExtendedType typedef, int line) {
-        final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(typedef.getQName(), line);
+    public static TypeDefinitionBuilder createTypedef(ExtendedType typedef, String moduleName, int line) {
+        final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(moduleName, line, typedef.getQName());
         builder.setPath(typedef.getPath());
         builder.setDefaultValue(typedef.getDefaultValue());
         builder.setUnits(typedef.getUnits());
@@ -854,8 +855,9 @@ public final class ParserUtils {
         return builder;
     }
 
-    public static UnknownSchemaNodeBuilder createUnknownSchemaNode(UnknownSchemaNode unknownNode, int line) {
-        final UnknownSchemaNodeBuilder builder = new UnknownSchemaNodeBuilder(line, unknownNode.getQName());
+    public static UnknownSchemaNodeBuilder createUnknownSchemaNode(UnknownSchemaNode unknownNode, String moduleName,
+            int line) {
+        final UnknownSchemaNodeBuilder builder = new UnknownSchemaNodeBuilder(moduleName, line, unknownNode.getQName());
         builder.setPath(unknownNode.getPath());
         builder.setUnknownNodes(unknownNode.getUnknownSchemaNodes());
         builder.setDescription(unknownNode.getDescription());
@@ -1084,7 +1086,8 @@ public final class ParserUtils {
         tc.addRanges(oldExtendedType.getRanges());
 
         final TypeConstraints constraints = findConstraintsFromTypeBuilder(newBaseType, tc, modules, module, null);
-        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(oldExtendedType.getQName(), line);
+        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(module.getModuleName(), line,
+                oldExtendedType.getQName());
         newType.setTypedef(newBaseType);
         newType.setPath(oldExtendedType.getPath());
         newType.setDescription(oldExtendedType.getDescription());
@@ -1120,7 +1123,8 @@ public final class ParserUtils {
         final TypeConstraints tc = new TypeConstraints(module.getName(), line);
 
         final TypeConstraints constraints = findConstraintsFromTypeDefinition(newBaseType, tc);
-        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(oldExtendedType.getQName(), line);
+        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(module.getModuleName(), line,
+                oldExtendedType.getQName());
         newType.setType(newBaseType);
         newType.setPath(oldExtendedType.getPath());
         newType.setDescription(oldExtendedType.getDescription());
index 44bb56be1c1e9b51e986661ba74b9527d6ed5abf..9e57d80aa9fe60991a2b2644e4244bc9b7ca8424 100644 (file)
@@ -7,16 +7,10 @@
  */
 package org.opendaylight.controller.yang.parser.util;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.opendaylight.controller.yang.model.api.MustDefinition;
-import org.opendaylight.controller.yang.parser.builder.api.Builder;
-import org.opendaylight.controller.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
+import org.opendaylight.controller.yang.parser.builder.api.AbstractBuilder;
 
-public final class RefineHolder implements Builder {
-    private Builder parent;
-    private final int line;
+public final class RefineHolder extends AbstractBuilder {
     private final String name;
     private String defaultStr;
     private String description;
@@ -27,26 +21,10 @@ public final class RefineHolder implements Builder {
     private MustDefinition must;
     private Integer minElements;
     private Integer maxElements;
-    private final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
 
-    public RefineHolder(final int line, final String name) {
+    public RefineHolder(final String moduleName, final int line, final String name) {
+        super(moduleName, line);
         this.name = name;
-        this.line = line;
-    }
-
-    @Override
-    public int getLine() {
-        return line;
-    }
-
-    @Override
-    public Builder getParent() {
-        return parent;
-    }
-
-    @Override
-    public void setParent(final Builder parent) {
-        this.parent = parent;
     }
 
     public String getDefaultStr() {
@@ -125,16 +103,6 @@ public final class RefineHolder implements Builder {
         return name;
     }
 
-    @Override
-    public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
-        return addedUnknownNodes;
-    }
-
-    @Override
-    public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
-        addedUnknownNodes.add(unknownNode);
-    }
-
     @Override
     public Object build() {
         return null;
@@ -233,7 +201,7 @@ public final class RefineHolder implements Builder {
 
     @Override
     public String toString() {
-        return "revine " + name;
+        return "refine " + name;
     }
 
 }
index 69c90caadf95178d15cfcb1d93008d485c010812..11d00cc05c7c59de00c9513ef22877d1bbc56d80 100644 (file)
@@ -96,38 +96,37 @@ public class RefineUtils {
      *            grouping which should contains node to refine
      * @param refine
      *            refine object containing informations about refine
-     * @param moduleName
-     *            current module name
      * @return
      */
     public static SchemaNodeBuilder getRefineNodeFromGroupingDefinition(final GroupingDefinition grouping,
-            final RefineHolder refine, final String moduleName) {
-        SchemaNodeBuilder result = null;
+            final RefineHolder refine) {
+        final String moduleName = refine.getModuleName();
         final int line = refine.getLine();
+        SchemaNodeBuilder result = null;
         final Object lookedUpNode = findRefineTargetNode(grouping, refine.getName());
         if (lookedUpNode instanceof LeafSchemaNode) {
-            result = createLeafBuilder((LeafSchemaNode) lookedUpNode, line);
+            result = createLeafBuilder((LeafSchemaNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof ContainerSchemaNode) {
-            result = createContainer((ContainerSchemaNode) lookedUpNode, line);
+            result = createContainer((ContainerSchemaNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof ListSchemaNode) {
-            result = createList((ListSchemaNode) lookedUpNode, line);
+            result = createList((ListSchemaNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof LeafListSchemaNode) {
-            result = createLeafList((LeafListSchemaNode) lookedUpNode, line);
+            result = createLeafList((LeafListSchemaNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof ChoiceNode) {
-            result = createChoice((ChoiceNode) lookedUpNode, line);
+            result = createChoice((ChoiceNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof AnyXmlSchemaNode) {
-            result = createAnyXml((AnyXmlSchemaNode) lookedUpNode, line);
+            result = createAnyXml((AnyXmlSchemaNode) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof GroupingDefinition) {
-            result = createGrouping((GroupingDefinition) lookedUpNode, line);
+            result = createGrouping((GroupingDefinition) lookedUpNode, moduleName, line);
         } else if (lookedUpNode instanceof TypeDefinition) {
-            result = createTypedef((ExtendedType) lookedUpNode, line);
+            result = createTypedef((ExtendedType) lookedUpNode, moduleName, line);
         } else {
             throw new YangParseException(moduleName, line, "Target '" + refine.getName() + "' can not be refined");
         }
         return result;
     }
 
-    public static void refineLeaf(LeafSchemaNodeBuilder leaf, RefineHolder refine, int line) {
+    public static void refineLeaf(LeafSchemaNodeBuilder leaf, RefineHolder refine) {
         String defaultStr = refine.getDefaultStr();
         Boolean mandatory = refine.isMandatory();
         MustDefinition must = refine.getMust();
@@ -256,8 +255,9 @@ public class RefineUtils {
      *            refine object containing information about refine process
      */
     public static void checkRefine(SchemaNodeBuilder node, RefineHolder refine) {
-        String name = node.getQName().getLocalName();
+        String moduleName = refine.getModuleName();
         int line = refine.getLine();
+        String name = node.getQName().getLocalName();
 
         String defaultStr = refine.getDefaultStr();
         Boolean mandatory = refine.isMandatory();
@@ -267,64 +267,66 @@ public class RefineUtils {
         Integer max = refine.getMaxElements();
 
         if (node instanceof AnyXmlBuilder) {
-            checkRefineDefault(node, defaultStr, line);
-            checkRefinePresence(node, presence, line);
-            checkRefineMinMax(name, line, min, max);
+            checkRefineDefault(node, defaultStr, moduleName, line);
+            checkRefinePresence(node, presence, moduleName, line);
+            checkRefineMinMax(name, min, max, moduleName, line);
         } else if (node instanceof ChoiceBuilder) {
-            checkRefinePresence(node, presence, line);
-            checkRefineMust(node, must, line);
-            checkRefineMinMax(name, line, min, max);
+            checkRefinePresence(node, presence, moduleName, line);
+            checkRefineMust(node, must, moduleName, line);
+            checkRefineMinMax(name, min, max, moduleName, line);
         } else if (node instanceof ContainerSchemaNodeBuilder) {
-            checkRefineDefault(node, defaultStr, line);
-            checkRefineMandatory(node, mandatory, line);
-            checkRefineMust(node, must, line);
-            checkRefineMinMax(name, line, min, max);
+            checkRefineDefault(node, defaultStr, moduleName, line);
+            checkRefineMandatory(node, mandatory, moduleName, line);
+            checkRefineMust(node, must, moduleName, line);
+            checkRefineMinMax(name, min, max, moduleName, line);
         } else if (node instanceof LeafSchemaNodeBuilder) {
-            checkRefinePresence(node, presence, line);
-            checkRefineMinMax(name, line, min, max);
+            checkRefinePresence(node, presence, moduleName, line);
+            checkRefineMinMax(name, min, max, moduleName, line);
         } else if (node instanceof LeafListSchemaNodeBuilder || node instanceof ListSchemaNodeBuilder) {
-            checkRefineDefault(node, defaultStr, line);
-            checkRefinePresence(node, presence, line);
-            checkRefineMandatory(node, mandatory, line);
+            checkRefineDefault(node, defaultStr, moduleName, line);
+            checkRefinePresence(node, presence, moduleName, line);
+            checkRefineMandatory(node, mandatory, moduleName, line);
         } else if (node instanceof GroupingBuilder || node instanceof TypeDefinitionBuilder
                 || node instanceof UsesNodeBuilder) {
-            checkRefineDefault(node, defaultStr, line);
-            checkRefinePresence(node, presence, line);
-            checkRefineMandatory(node, mandatory, line);
-            checkRefineMust(node, must, line);
-            checkRefineMinMax(name, line, min, max);
+            checkRefineDefault(node, defaultStr, moduleName, line);
+            checkRefinePresence(node, presence, moduleName, line);
+            checkRefineMandatory(node, mandatory, moduleName, line);
+            checkRefineMust(node, must, moduleName, line);
+            checkRefineMinMax(name, min, max, moduleName, line);
         }
     }
 
-    private static void checkRefineDefault(SchemaNodeBuilder node, String defaultStr, int line) {
+    private static void checkRefineDefault(SchemaNodeBuilder node, String defaultStr, String moduleName, int line) {
         if (defaultStr != null) {
-            throw new YangParseException(line, "Can not refine 'default' for '" + node.getQName().getLocalName() + "'.");
+            throw new YangParseException(moduleName, line, "Can not refine 'default' for '"
+                    + node.getQName().getLocalName() + "'.");
         }
     }
 
-    private static void checkRefineMandatory(SchemaNodeBuilder node, Boolean mandatory, int line) {
+    private static void checkRefineMandatory(SchemaNodeBuilder node, Boolean mandatory, String moduleName, int line) {
         if (mandatory != null) {
-            throw new YangParseException(line, "Can not refine 'mandatory' for '" + node.getQName().getLocalName()
-                    + "'.");
+            throw new YangParseException(moduleName, line, "Can not refine 'mandatory' for '"
+                    + node.getQName().getLocalName() + "'.");
         }
     }
 
-    private static void checkRefinePresence(SchemaNodeBuilder node, Boolean presence, int line) {
+    private static void checkRefinePresence(SchemaNodeBuilder node, Boolean presence, String moduleName, int line) {
         if (presence != null) {
-            throw new YangParseException(line, "Can not refine 'presence' for '" + node.getQName().getLocalName()
-                    + "'.");
+            throw new YangParseException(moduleName, line, "Can not refine 'presence' for '"
+                    + node.getQName().getLocalName() + "'.");
         }
     }
 
-    private static void checkRefineMust(SchemaNodeBuilder node, MustDefinition must, int line) {
+    private static void checkRefineMust(SchemaNodeBuilder node, MustDefinition must, String moduleName, int line) {
         if (must != null) {
-            throw new YangParseException(line, "Can not refine 'must' for '" + node.getQName().getLocalName() + "'.");
+            throw new YangParseException(moduleName, line, "Can not refine 'must' for '"
+                    + node.getQName().getLocalName() + "'.");
         }
     }
 
-    private static void checkRefineMinMax(String refineTargetName, int refineLine, Integer min, Integer max) {
+    private static void checkRefineMinMax(String refineTargetName, Integer min, Integer max, String moduleName, int line) {
         if (min != null || max != null) {
-            throw new YangParseException(refineLine, "Can not refine 'min-elements' or 'max-elements' for '"
+            throw new YangParseException(moduleName, line, "Can not refine 'min-elements' or 'max-elements' for '"
                     + refineTargetName + "'.");
         }
     }
@@ -343,10 +345,10 @@ public class RefineUtils {
      *            node to refine
      * @param refine
      *            refine object containing information about refine process
-     * @param line
-     *            current line in yang model
      */
-    public static void refineDefault(final Builder node, final RefineHolder refine, final int line) {
+    public static void refineDefault(final Builder node, final RefineHolder refine) {
+        final String moduleName = refine.getModuleName();
+        final int line = refine.getLine();
         Class<? extends Builder> cls = node.getClass();
 
         String description = refine.getDescription();
@@ -355,7 +357,7 @@ public class RefineUtils {
                 Method method = cls.getDeclaredMethod("setDescription", String.class);
                 method.invoke(node, description);
             } catch (Exception e) {
-                throw new YangParseException(line, "Cannot refine description in " + cls.getName(), e);
+                throw new YangParseException(moduleName, line, "Cannot refine description in " + cls.getName(), e);
             }
         }
 
@@ -365,7 +367,7 @@ public class RefineUtils {
                 Method method = cls.getDeclaredMethod("setReference", String.class);
                 method.invoke(node, reference);
             } catch (Exception e) {
-                throw new YangParseException(line, "Cannot refine reference in " + cls.getName(), e);
+                throw new YangParseException(moduleName, line, "Cannot refine reference in " + cls.getName(), e);
             }
         }
 
@@ -375,7 +377,7 @@ public class RefineUtils {
                 Method method = cls.getDeclaredMethod("setConfiguration", Boolean.class);
                 method.invoke(node, config);
             } catch (Exception e) {
-                throw new YangParseException(line, "Cannot refine config in " + cls.getName(), e);
+                throw new YangParseException(moduleName, line, "Cannot refine config in " + cls.getName(), e);
             }
         }
     }
@@ -392,9 +394,9 @@ public class RefineUtils {
      */
     public static void performRefine(SchemaNodeBuilder nodeToRefine, RefineHolder refine, int line) {
         checkRefine(nodeToRefine, refine);
-        refineDefault(nodeToRefine, refine, line);
+        refineDefault(nodeToRefine, refine);
         if (nodeToRefine instanceof LeafSchemaNodeBuilder) {
-            refineLeaf((LeafSchemaNodeBuilder) nodeToRefine, refine, line);
+            refineLeaf((LeafSchemaNodeBuilder) nodeToRefine, refine);
         } else if (nodeToRefine instanceof ContainerSchemaNodeBuilder) {
             refineContainer((ContainerSchemaNodeBuilder) nodeToRefine, refine, line);
         } else if (nodeToRefine instanceof ListSchemaNodeBuilder) {
index 4d2c5b582321c907860b801edeb57499a2ab9f6b..08422c839242e079dcf49392b3eb049a6cd54b04 100644 (file)
@@ -229,7 +229,7 @@ public final class TypeConstraints {
 
         for (RangeConstraint range : typeRange) {
             if (range.getMin() instanceof UnknownBoundaryNumber || range.getMax() instanceof UnknownBoundaryNumber) {
-                throw new YangParseException(line, "Unresolved range constraints");
+                throw new YangParseException(moduleName, line, "Unresolved range constraints");
             }
             final long min = range.getMin().longValue();
             final long max = range.getMax().longValue();
@@ -268,7 +268,7 @@ public final class TypeConstraints {
 
         for (RangeConstraint range : typeRange) {
             if (range.getMin() instanceof UnknownBoundaryNumber || range.getMax() instanceof UnknownBoundaryNumber) {
-                throw new YangParseException(line, "Unresolved range constraints");
+                throw new YangParseException(moduleName, line, "Unresolved range constraints");
             }
             final long min = range.getMin().longValue();
             final long max = range.getMax().longValue();
@@ -308,7 +308,7 @@ public final class TypeConstraints {
 
         for (LengthConstraint length : typeLength) {
             if (length.getMin() instanceof UnknownBoundaryNumber || length.getMax() instanceof UnknownBoundaryNumber) {
-                throw new YangParseException(line, "Unresolved length constraints");
+                throw new YangParseException(moduleName, line, "Unresolved length constraints");
             }
             final long min = length.getMin().longValue();
             final long max = length.getMax().longValue();
@@ -347,7 +347,7 @@ public final class TypeConstraints {
 
         for (LengthConstraint length : typeLength) {
             if (length.getMin() instanceof UnknownBoundaryNumber || length.getMax() instanceof UnknownBoundaryNumber) {
-                throw new YangParseException(line, "Unresolved length constraints");
+                throw new YangParseException(moduleName, line, "Unresolved length constraints");
             }
             final long min = length.getMin().longValue();
             final long max = length.getMax().longValue();
index c9fd7235599b968b7f5f9dcef7fdc4d1a6b371e2..6939261a5701477676092acc5c2a4f8416ea8e98 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.yang.parser.util;
 
 public class YangParseException extends RuntimeException {
-
     private static final long serialVersionUID = 1239548963471793178L;
 
     public YangParseException(final String errorMsg) {
@@ -19,24 +18,15 @@ public class YangParseException extends RuntimeException {
         super(errorMsg, exception);
     }
 
-    public YangParseException(final int line, final String errorMsg) {
-        super("Error on line " + line + ": " + errorMsg);
-    }
-
-    public YangParseException(final int line, final String errorMsg,
-            final Exception exception) {
-        super("Error on line " + line + ": " + errorMsg, exception);
-    }
-
     public YangParseException(final String moduleName, final int line,
             final String errorMsg) {
-        super("Error in module '" + moduleName + "' on line " + line + ": "
+        super("Error in module '" + moduleName + "' at line " + line + ": "
                 + errorMsg);
     }
 
     public YangParseException(final String moduleName, final int line,
             final String errorMsg, final Exception exception) {
-        super("Error in module '" + moduleName + "' on line " + line + ": "
+        super("Error in module '" + moduleName + "' at line " + line + ": "
                 + errorMsg, exception);
     }
 
index fb73bd6e5b7eb6937ce95e9fd70bb4450b8bc955..0412013405c5ac8c317bb169fe28f359496a26f2 100644 (file)
@@ -13,6 +13,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 
 import org.junit.Test;
@@ -43,8 +44,7 @@ public class YangParserNegativeTest {
                 fail("YangParseException should by thrown");
             }
         } catch (YangParseException e) {
-            assertTrue(e.getMessage().contains(
-                    "Error in module 'test2' on line 24: Referenced type 'int-ext' not found."));
+            assertEquals(e.getMessage(), "Error in module 'test2' at line 24: Referenced type 'int-ext' not found.");
         }
     }
 
@@ -116,8 +116,8 @@ public class YangParserNegativeTest {
                 fail("YangParseException should by thrown");
             }
         } catch (YangParseException e) {
-            assertTrue(e.getMessage()
-                    .contains("Error in module 'container' on line 10: Duplicate node found at line 6"));
+            String expected = "Error in module 'container' at line 10: Can not add 'container foo': node with same name already declared at line 6";
+            assertEquals(expected, e.getMessage());
         }
     }
 
@@ -130,8 +130,8 @@ public class YangParserNegativeTest {
                 fail("YangParseException should by thrown");
             }
         } catch (YangParseException e) {
-            assertTrue(e.getMessage().contains(
-                    "Error in module 'container-list' on line 10: Duplicate node found at line 6"));
+            String expected = "Error in module 'container-list' at line 10: Can not add 'list foo': node with same name already declared at line 6";
+            assertEquals(expected, e.getMessage());
         }
     }
 
@@ -144,8 +144,8 @@ public class YangParserNegativeTest {
                 fail("YangParseException should by thrown");
             }
         } catch (YangParseException e) {
-            assertTrue(e.getMessage().contains(
-                    "Error in module 'container-leaf' on line 10: Duplicate node found at line 6"));
+            String expected = "Error in module 'container-leaf' at line 10: Can not add 'leaf foo': node with same name already declared at line 6";
+            assertEquals(expected, e.getMessage());
         }
     }
 
@@ -158,7 +158,40 @@ public class YangParserNegativeTest {
                 fail("YangParseException should by thrown");
             }
         } catch (YangParseException e) {
-            assertTrue(e.getMessage().contains("Error in module 'typedef' on line 10: Duplicate node found at line 6"));
+            String expected = "Error in module 'typedef' at line 10: typedef with same name 'int-ext' already declared at line 6";
+            assertEquals(expected, e.getMessage());
+        }
+    }
+
+    @Test
+    public void testDuplicityInAugmentTarget1() throws Exception {
+        try {
+            try (InputStream stream1 = new FileInputStream(getClass().getResource(
+                    "/negative-scenario/duplicity/augment0.yang").getPath());
+                    InputStream stream2 = new FileInputStream(getClass().getResource(
+                            "/negative-scenario/duplicity/augment1.yang").getPath())) {
+                TestUtils.loadModules(Arrays.asList(stream1, stream2));
+                fail("YangParseException should by thrown");
+            }
+        } catch (YangParseException e) {
+            String expected = "Error in module 'augment1' at line 11: Can not add 'leaf id' to node 'bar' in module 'augment0': node with same name already declared at line 9";
+            assertEquals(expected, e.getMessage());
+        }
+    }
+
+    @Test
+    public void testDuplicityInAugmentTarget2() throws Exception {
+        try {
+            try (InputStream stream1 = new FileInputStream(getClass().getResource(
+                    "/negative-scenario/duplicity/augment0.yang").getPath());
+                    InputStream stream2 = new FileInputStream(getClass().getResource(
+                            "/negative-scenario/duplicity/augment2.yang").getPath())) {
+                TestUtils.loadModules(Arrays.asList(stream1, stream2));
+                fail("YangParseException should by thrown");
+            }
+        } catch (YangParseException e) {
+            String expected = "Error in module 'augment2' at line 11: Can not add 'anyxml delta' to node 'choice-ext' in module 'augment0': case with same name already declared at line 18";
+            assertEquals(expected, e.getMessage());
         }
     }
 
index f2478e741dddeb3dd65db2740f334e599ffe0274..83109ea9b1b590e2e4accef06bdf1bc6ceb874fe 100644 (file)
@@ -195,7 +195,7 @@ public class YangParserTest {
         // test DataNodeContainer args
         assertEquals(0, interfaces.getTypeDefinitions().size());
         assertEquals(1, interfaces.getChildNodes().size());
-        assertEquals(0, interfaces.getGroupings().size());
+        assertEquals(1, interfaces.getGroupings().size());
         assertEquals(0, interfaces.getUses().size());
 
         ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
index d9d506438337ad7df2d390e063e3d26f175243b6..bff9543009b0e2b6b9d0c5863f171e42ae2c3cbb 100644 (file)
@@ -2,7 +2,7 @@ module types {
     yang-version 1;
     namespace "urn:simple.types.test";
     prefix "t";
-    
+
     organization "opendaylight";
     contact "http://www.opendaylight.org/";
     description "This is types-data test description";
@@ -37,7 +37,7 @@ module types {
             length "6..10";
         }
     }
-    
+
     typedef string-ext3 {
         type string-ext2 {
             pattern "[b-u]*";
@@ -77,21 +77,24 @@ module types {
     }
 
     container interfaces {
-         list ifEntry {
-             key "ifIndex";
+        grouping ifEntry {
+            container augment-holder;
+        }
+        list ifEntry {
+            key "ifIndex";
 
-             leaf ifIndex {
-                 type uint32;
-                 units minutes;
-             }
+            leaf ifIndex {
+                type uint32;
+                units minutes;
+            }
 
-             leaf ifMtu {
-                 type int32;
-             }
+            leaf ifMtu {
+                type int32;
+            }
 
-             min-elements 1;
-             max-elements 11;
-         }
+            min-elements 1;
+            max-elements 11;
+        }
     }
 
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment0.yang b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment0.yang
new file mode 100644 (file)
index 0000000..ff8519c
--- /dev/null
@@ -0,0 +1,25 @@
+module augment0 {
+    yang-version 1;
+    namespace "urn:simple.augment0.demo";
+    prefix "a0";
+
+    container foo {
+        description "foo container";
+        container bar {
+            leaf id {
+                type int8;
+            }
+            typedef int-ext {
+                type int8 {
+                    range "5..10";
+                }
+            }
+            choice choice-ext {
+                leaf delta {
+                    type int8;
+                }
+            }
+        }
+    }
+
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment1.yang b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment1.yang
new file mode 100644 (file)
index 0000000..6afb493
--- /dev/null
@@ -0,0 +1,16 @@
+module augment1 {
+    yang-version 1;
+    namespace "urn:simple.augment1.demo";
+    prefix "a1";
+
+    import augment0 {
+        prefix "a0";
+    }
+
+    augment "/a0:foo/a0:bar" {
+        leaf id {
+            type string;
+        }
+    }
+
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment2.yang b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/duplicity/augment2.yang
new file mode 100644 (file)
index 0000000..4d87619
--- /dev/null
@@ -0,0 +1,14 @@
+module augment2 {
+    yang-version 1;
+    namespace "urn:simple.augment2.demo";
+    prefix "a2";
+
+    import augment0 {
+        prefix "a0";
+    }
+
+    augment "/a0:foo/a0:bar/a0:choice-ext" {
+        anyxml delta;
+    }
+
+}
index 487c10cbf95cefc5c5e6a916a51442bbb533211d..53ffc2ea0befcde78208461fa5831ef0bcebdf09 100755 (executable)
-/*\r
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.controller.yang.data.impl;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-import java.io.PrintStream;\r
-import java.net.URI;\r
-import java.util.Date;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.opendaylight.controller.yang.common.QName;\r
-import org.opendaylight.controller.yang.data.api.CompositeNode;\r
-import org.opendaylight.controller.yang.data.api.Node;\r
-import org.opendaylight.controller.yang.data.api.SimpleNode;\r
-import org.opendaylight.controller.yang.model.api.ListSchemaNode;\r
-import org.opendaylight.controller.yang.model.api.SchemaContext;\r
-import org.w3c.dom.Document;\r
-\r
-/**\r
- * @author michal.rehak\r
- *\r
- */\r
-public class NodeUtilsTest {\r
-    \r
-    private QName qName;\r
-    private CompositeNode network;\r
-\r
-    /**\r
-     * @throws Exception\r
-     */\r
-    @Before\r
-    public void setUp() throws Exception {\r
-        qName = new QName(\r
-                new URI("urn:ietf:params:xml:ns:netconf:base:1.0"), \r
-                new Date(42), "yang-data-impl-mutableTest");\r
-        network = NodeHelper.buildTestConfigTree(qName);\r
-    }\r
-\r
-    /**\r
-     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildPath(org.opendaylight.controller.yang.data.api.Node)}.\r
-     * @throws Exception \r
-     */\r
-    @Test\r
-    public void testBuildPath() throws Exception {\r
-        SimpleNode<?> needle = network.getCompositesByName("topologies").iterator().next()\r
-            .getCompositesByName("topology").iterator().next()\r
-            .getSimpleNodesByName("topology-id").iterator().next();\r
-        String breadCrumbs = NodeUtils.buildPath(needle);\r
-        \r
-        Assert.assertEquals("network.topologies.topology.topology-id", breadCrumbs);\r
-    }\r
-\r
-    /**\r
-     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildShadowDomTree(org.opendaylight.controller.yang.data.api.CompositeNode)}.\r
-     * @throws Exception \r
-     */\r
-    @Test\r
-    public void testBuildShadowDomTree() throws Exception {\r
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);\r
-        ByteArrayOutputStream actual = new ByteArrayOutputStream();\r
-        NodeHelper.dumpDoc(networkShadow, new PrintStream(actual));\r
-        \r
-        Assert.assertEquals(2760, new String(actual.toByteArray()).length());\r
-    }\r
-\r
-    /**\r
-     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#findNodeByXpath(org.w3c.dom.Document, java.lang.String)}.\r
-     * @throws Exception \r
-     */\r
-    @Test\r
-    public void testFindNodeByXpath() throws Exception {\r
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);\r
-        SimpleNode<String> needle = NodeUtils.findNodeByXpath(networkShadow, \r
-                "//node[node-id='nodeId_19']//termination-point[2]/tp-id");\r
-        Assert.assertNotNull(needle);\r
-        Assert.assertEquals("tpId_18", needle.getValue());\r
-    }\r
-\r
-    /**\r
-     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildNodeMap(java.util.List)}.\r
-     */\r
-    @Test\r
-    public void testBuildNodeMap() {\r
-        CompositeNode topology = network.getCompositesByName("topologies").iterator().next()\r
-            .getCompositesByName("topology").iterator().next();\r
-        \r
-        Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getChildren());\r
-        Assert.assertEquals(3, nodeMap.size());\r
-    }\r
-    \r
-    /**\r
-     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.controller.yang.model.api.SchemaContext)}.\r
-     */\r
-    @Test\r
-    public void testBuildMapOfListNodes() {\r
-        SchemaContext schemaCtx = NodeHelper.loadSchemaContext();\r
-        Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(schemaCtx);\r
-        Assert.assertEquals(5, mapOfLists.size());\r
-    }\r
-\r
-}\r
+/*
+ * 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.yang.data.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.net.URI;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.yang.common.QName;
+import org.opendaylight.controller.yang.data.api.CompositeNode;
+import org.opendaylight.controller.yang.data.api.Node;
+import org.opendaylight.controller.yang.data.api.SimpleNode;
+import org.opendaylight.controller.yang.model.api.ListSchemaNode;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.w3c.dom.Document;
+
+/**
+ * @author michal.rehak
+ *
+ */
+public class NodeUtilsTest {
+    
+    private QName qName;
+    private CompositeNode network;
+
+    /**
+     * @throws Exception
+     */
+    @Before
+    public void setUp() throws Exception {
+        qName = new QName(
+                new URI("urn:ietf:params:xml:ns:netconf:base:1.0"), 
+                new Date(42), "yang-data-impl-mutableTest");
+        network = NodeHelper.buildTestConfigTree(qName);
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildPath(org.opendaylight.controller.yang.data.api.Node)}.
+     * @throws Exception 
+     */
+    @Test
+    public void testBuildPath() throws Exception {
+        SimpleNode<?> needle = network.getCompositesByName("topologies").iterator().next()
+            .getCompositesByName("topology").iterator().next()
+            .getSimpleNodesByName("topology-id").iterator().next();
+        String breadCrumbs = NodeUtils.buildPath(needle);
+        
+        Assert.assertEquals("network.topologies.topology.topology-id", breadCrumbs);
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildShadowDomTree(org.opendaylight.controller.yang.data.api.CompositeNode)}.
+     * @throws Exception 
+     */
+    @Test
+    public void testBuildShadowDomTree() throws Exception {
+        Document networkShadow = NodeUtils.buildShadowDomTree(network);
+        ByteArrayOutputStream actual = new ByteArrayOutputStream();
+        NodeHelper.dumpDoc(networkShadow, new PrintStream(actual));
+        
+        Assert.assertEquals(2760, new String(actual.toByteArray()).length());
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#findNodeByXpath(org.w3c.dom.Document, java.lang.String)}.
+     * @throws Exception 
+     */
+    @Test
+    public void testFindNodeByXpath() throws Exception {
+        Document networkShadow = NodeUtils.buildShadowDomTree(network);
+        SimpleNode<String> needle = NodeUtils.findNodeByXpath(networkShadow, 
+                "//node[node-id='nodeId_19']//termination-point[2]/tp-id");
+        Assert.assertNotNull(needle);
+        Assert.assertEquals("tpId_18", needle.getValue());
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildNodeMap(java.util.List)}.
+     */
+    @Test
+    public void testBuildNodeMap() {
+        CompositeNode topology = network.getCompositesByName("topologies").iterator().next()
+            .getCompositesByName("topology").iterator().next();
+        
+        Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getChildren());
+        Assert.assertEquals(3, nodeMap.size());
+    }
+    
+    /**
+     * Test method for {@link org.opendaylight.controller.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.controller.yang.model.api.SchemaContext)}.
+     */
+    @Test
+    public void testBuildMapOfListNodes() {
+        SchemaContext schemaCtx = NodeHelper.loadSchemaContext();
+        Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(schemaCtx);
+        Assert.assertEquals(5, mapOfLists.size());
+    }
+
+}
index 7fd9bc17d1e4cf05c1a69d0bb169d3e6168ee90a..9ff3f9185053076398a6bd601b5dc8f56bae2b3f 100644 (file)
@@ -58,7 +58,6 @@ import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.IObjectReader;
 import org.opendaylight.controller.sal.utils.ObjectReader;
 import org.opendaylight.controller.sal.utils.ObjectWriter;
-import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.controller.switchmanager.IInventoryListener;
@@ -888,10 +887,8 @@ CommandProvider {
         }
 
         // copy node properties from plugin
-        if (props != null) {
-            for (Property prop : props) {
-                propMap.put(prop.getName(), prop);
-            }
+        for (Property prop : props) {
+            propMap.put(prop.getName(), prop);
         }
 
         if (propMapCurr == null) {
@@ -934,7 +931,6 @@ CommandProvider {
     @Override
     public void updateNodeConnector(NodeConnector nodeConnector,
             UpdateType type, Set<Property> props) {
-        Node node = nodeConnector.getNode();
         Map<String, Property> propMap = new HashMap<String, Property>();
 
         log.debug("updateNodeConnector: {} type {} props {} for container {}",
@@ -954,14 +950,12 @@ CommandProvider {
                 }
             } else {
                 addNodeConnectorProp(nodeConnector, null);
-                addNodeProps(node, null);
             }
 
             addSpanPort(nodeConnector);
             break;
         case REMOVED:
             removeNodeConnectorAllProps(nodeConnector);
-            removeNodeProps(node);
 
             // clean up span config
             removeSpanPort(nodeConnector);
@@ -990,23 +984,15 @@ CommandProvider {
      */
     @Override
     public Map<String, Property> getNodeProps(Node node) {
-        if (isDefaultContainer) {
-            Map<String, Property> rv = null;
-            if (this.nodeProps != null) {
-                rv = this.nodeProps.get(node);
-                if (rv != null) {
-                    /* make a copy of it */
-                    rv = new HashMap<String, Property>(rv);
-                }
+        Map<String, Property> rv = new HashMap<String, Property>();
+        if (this.nodeProps != null) {
+            rv = this.nodeProps.get(node);
+            if (rv != null) {
+                /* make a copy of it */
+                rv = new HashMap<String, Property>(rv);
             }
-            return rv;
-        } else {
-            // get it from default container
-            ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class,
-                            GlobalConstants.DEFAULT.toString(), this);
-            return defaultSwitchManager.getNodeProps(node);
         }
+        return rv;
     }
 
     @Override
@@ -1036,7 +1022,7 @@ CommandProvider {
                 return;
             }
             if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
-                log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
+                log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
                 return;
             }
         }
@@ -1135,24 +1121,15 @@ CommandProvider {
     }
 
     @Override
-    public Map<String, Property> getNodeConnectorProps(
-            NodeConnector nodeConnector) {
-        if (isDefaultContainer) {
-            Map<String, Property> rv = null;
-            if (this.nodeConnectorProps != null) {
-                rv = this.nodeConnectorProps.get(nodeConnector);
-                if (rv != null) {
-                    rv = new HashMap<String, Property>(rv);
-                }
+    public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
+        Map<String, Property> rv = new HashMap<String, Property>();
+        if (this.nodeConnectorProps != null) {
+            rv = this.nodeConnectorProps.get(nodeConnector);
+            if (rv != null) {
+                rv = new HashMap<String, Property>(rv);
             }
-            return rv;
-        } else {
-            // get it from default container
-            ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class,
-                            GlobalConstants.DEFAULT.toString(), this);
-            return defaultSwitchManager.getNodeConnectorProps(nodeConnector);
         }
+        return rv;
     }
 
     @Override