<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>
# 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.
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()) {
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;
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;
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;
}
public enum DiscoveryPeriod {
- INTERVAL(300),
- TIMEOUT (60),
- AGEOUT (120);
+ INTERVAL (300),
+ AGEOUT (120),
+ THRESHOLD (10);
private int time; // sec
private int tick; // tick
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) {
logger.error("Caught exception ", e);
}
addEdge(edge, props);
- pendingMap.put(dstNodeConnector, 0);
logger.trace("Received discovery packet for Edge {}", edge);
return true;
}
- if (pendingMap.keySet().contains(nodeConnector)) {
+ if (holdTime.keySet().contains(nodeConnector)) {
return true;
}
- if (waitingList.contains(nodeConnector)) {
+ if (stagingList.contains(nodeConnector)) {
return true;
}
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);
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);
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);
}
}
}
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);
+ }
}
}
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);
}
}
}
if (!isTracked(nodeConnector)) {
- waitingList.add(nodeConnector);
+ stagingList.add(nodeConnector);
discoveryConsistencyCheckCorrected++;
logger.debug("ConsistencyChecker: add back untracked {}", nodeConnector);
continue;
// 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();
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);
}
}
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);
* 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;
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);
}
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");
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");
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) {
}
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) {
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) {
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) {
}
}
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;
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();
transmitQ = null;
readyListHi = null;
readyListLo = null;
- waitingList = null;
- pendingMap = null;
+ stagingList = null;
+ holdTime = null;
edgeMap = null;
agingMap = null;
prodMap = null;
}
/**
- * 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);
}
/**
}
/**
- * 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;
}
}
package org.opendaylight.controller.protocol_plugin.openflow.internal;
+import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
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;
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;
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;
this.controller.removeSwitchStateListener(this);
this.inventoryShimInternalListeners.clear();
- this.containerMap.clear();
+ this.nodeConnectorContainerMap.clear();
+ this.nodeContainerMap.clear();
this.controller = null;
}
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);
}
}
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());
}
}
@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,
/*
* 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
/*
* 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
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);
}
}
}
+ 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);
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;
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;
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);
}
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;
-
+
}
-
+
}
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.*;
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);
- }
}
}
}
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);
}
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;
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());
}
}
+ 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;
+ }
+
}
--- /dev/null
+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());
+ }
+
+}
--- /dev/null
+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
}
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) {
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 {
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();
}
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);
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();
}
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();
--- /dev/null
+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
--- /dev/null
+/*
+ * 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;
+ }
+
+}
*/
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>();
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;
@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);
}
@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);
}
}
*/\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
}\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
*/
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;
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;
- }
-
}
*/
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.
*
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();
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;
@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
@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
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 {
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();
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);
}
}
// 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
@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
@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
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>();
}
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
this.mandatory = mandatory;
}
-
private final class ConstraintDefinitionImpl implements ConstraintDefinition {
private RevisionAwareXPath whenCondition;
private Set<MustDefinition> mustConstraints;
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 {
// 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();
// 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());
}
@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);
}
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;
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();
@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);
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;
}
} 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);
}
}
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;
}
@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);
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);
}
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);
}
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;
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();
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());
}
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() {
@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);
}
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;
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();
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);
}
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;
}
@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
@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
@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
@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
@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
@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
@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
@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
@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
// 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();
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();
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 {
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();
// 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());
}
@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);
}
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);
}
}
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);
}
}
}
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);
}
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);
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 {
}
refine.setParent(parent);
}
-
- path.add(refine.getName());
}
public RpcDefinitionBuilder addRpc(final int line, final QName qname) {
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);
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);
}
}
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;
}
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;
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;
}
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;
}
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);
}
}
- 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
// 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);
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 + "'.");
}
}
}
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);
}
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);
}
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();
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;
}
@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
@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
@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
@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
@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
@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
@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
@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
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();
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
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
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
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
@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
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
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);
}
}
/**
- * 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
}
if (newChild == null) {
- throw new YangParseException(usesNode.getLine(),
+ throw new YangParseException(usesNode.getModuleName(), usesNode.getLine(),
"Unknown member of target grouping while resolving uses node.");
}
}
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();
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.");
}
}
}
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);
}
}
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);
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();
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);
}
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);
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);
* 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++) {
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();
* 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;
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);
}
* 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);
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;
}
}
* 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;
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);
* 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);
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;
}
}
* 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;
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);
* @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);
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;
* 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);
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();
* 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;
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");
}
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;
}
}
* 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) {
result = false;
break;
} else {
- throw new YangParseException(ctx.getStart().getLine(),
+ throw new YangParseException(moduleName, ctx.getStart().getLine(),
"Failed to parse 'config' statement value: '" + value + "'.");
}
}
/**
* Parse type body and create UnknownType definition.
*
- * @param moduleName
- * name of current module
* @param typedefQName
* qname of current type
* @param ctx
* @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);
/**
* Create TypeDefinition object based on given type name and type body.
*
- * @param moduleName
- * current module name
* @param typeName
* name of type
* @param typeBody
* 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);
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)) {
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("/");
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);
}
}
- 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++) {
}
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++) {
}
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);
}
}
* 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) {
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);
}
}
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);
}
}
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);
}
}
}
}
correctAugmentChildPath(builder, target.getPath());
- target.addChildNode(builder);
+ target.addCase(builder);
}
}
* 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();
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());
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());
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());
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());
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());
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());
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());
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());
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());
*/
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;
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() {
return name;
}
- @Override
- public List<UnknownSchemaNodeBuilder> getUnknownNodeBuilders() {
- return addedUnknownNodes;
- }
-
- @Override
- public void addUnknownNodeBuilder(UnknownSchemaNodeBuilder unknownNode) {
- addedUnknownNodes.add(unknownNode);
- }
-
@Override
public Object build() {
return null;
@Override
public String toString() {
- return "revine " + name;
+ return "refine " + name;
}
}
* 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();
* 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();
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 + "'.");
}
}
* 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();
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);
}
}
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);
}
}
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);
}
}
}
*/
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) {
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();
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();
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();
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();
package org.opendaylight.controller.yang.parser.util;
public class YangParseException extends RuntimeException {
-
private static final long serialVersionUID = 1239548963471793178L;
public YangParseException(final String errorMsg) {
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);
}
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import org.junit.Test;
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.");
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
// 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");
yang-version 1;
namespace "urn:simple.types.test";
prefix "t";
-
+
organization "opendaylight";
contact "http://www.opendaylight.org/";
description "This is types-data test description";
length "6..10";
}
}
-
+
typedef string-ext3 {
type string-ext2 {
pattern "[b-u]*";
}
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;
+ }
}
}
--- /dev/null
+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;
+ }
+ }
+ }
+ }
+
+}
--- /dev/null
+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;
+ }
+ }
+
+}
--- /dev/null
+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;
+ }
+
+}
-/*\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());
+ }
+
+}
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;
}
// 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) {
@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 {}",
}
} else {
addNodeConnectorProp(nodeConnector, null);
- addNodeProps(node, null);
}
addSpanPort(nodeConnector);
break;
case REMOVED:
removeNodeConnectorAllProps(nodeConnector);
- removeNodeProps(node);
// clean up span config
removeSpanPort(nodeConnector);
*/
@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
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;
}
}
}
@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