<version>0.4.0-SNAPSHOT</version>
<dependencies>
- <dependency>
- <groupId>org.infinispan</groupId>
- <artifactId>infinispan-core</artifactId>
- <version>5.2.3.Final</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>clustering.services</artifactId>
<artifactId>clustering.services-implementation</artifactId>
<version>0.4.0-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>containermanager</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>containermanager.implementation</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </dependency>
</dependencies>
<properties>
<!-- Sonar jacoco plugin to get integration test coverage info -->
import static org.ops4j.pax.exam.CoreOptions.systemPackages;\r
import static org.ops4j.pax.exam.CoreOptions.systemProperty;\r
\r
+import java.util.List;\r
+import java.util.concurrent.CopyOnWriteArrayList;\r
+import java.util.concurrent.TimeUnit;\r
import java.net.InetAddress;\r
+import java.util.Dictionary;\r
import java.util.HashSet;\r
+import java.util.Hashtable;\r
+import java.util.Set;\r
import java.util.List;\r
import java.util.concurrent.ConcurrentMap;\r
\r
import org.opendaylight.controller.clustering.services.CacheConfigException;\r
import org.opendaylight.controller.clustering.services.CacheExistException;\r
import org.opendaylight.controller.clustering.services.CacheListenerAddException;\r
+import org.opendaylight.controller.clustering.services.IClusterGlobalServices;\r
import org.opendaylight.controller.clustering.services.IClusterServices;\r
+import org.opendaylight.controller.clustering.services.IClusterContainerServices;\r
import org.opendaylight.controller.clustering.services.IClusterServices.cacheMode;\r
import org.opendaylight.controller.clustering.services.IGetUpdates;\r
+import org.opendaylight.controller.clustering.services.ICacheUpdateAware;\r
+import org.opendaylight.controller.sal.utils.ServiceHelper;\r
+import org.opendaylight.controller.sal.core.UpdateType;\r
import org.ops4j.pax.exam.Option;\r
import org.ops4j.pax.exam.junit.Configuration;\r
import org.ops4j.pax.exam.junit.PaxExam;\r
import org.osgi.framework.Bundle;\r
import org.osgi.framework.BundleContext;\r
import org.osgi.framework.ServiceReference;\r
+import org.osgi.framework.ServiceRegistration;\r
import org.slf4j.Logger;\r
import org.slf4j.LoggerFactory;\r
+import java.util.concurrent.CountDownLatch;\r
\r
@RunWith(PaxExam.class)\r
public class ClusteringServicesIT {\r
private Logger log = LoggerFactory\r
- .getLogger(ClusteringServicesIT.class);\r
+ .getLogger(ClusteringServicesIT.class);\r
// get the OSGI bundle context\r
@Inject\r
private BundleContext bc;\r
-\r
private IClusterServices clusterServices = null;\r
+ private IClusterContainerServices clusterDefaultServices = null;\r
+ private IClusterGlobalServices clusterGlobalServices = null;\r
\r
// Configure the OSGi container\r
@Configuration\r
public Option[] config() {\r
return options(\r
- //\r
- systemProperty("logback.configurationFile").value(\r
- "file:" + PathUtils.getBaseDir()\r
- + "/src/test/resources/logback.xml"),\r
- // To start OSGi console for inspection remotely\r
- systemProperty("osgi.console").value("2401"),\r
- // Set the systemPackages (used by clustering)\r
- systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"),\r
- // List framework bundles\r
- mavenBundle("equinoxSDK381", "org.eclipse.equinox.console",\r
- "1.0.0.v20120522-1841"),\r
- mavenBundle("equinoxSDK381", "org.eclipse.equinox.util",\r
- "1.0.400.v20120522-2049"),\r
- mavenBundle("equinoxSDK381", "org.eclipse.osgi.services",\r
- "3.3.100.v20120522-1822"),\r
- mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds",\r
- "1.4.0.v20120522-1841"),\r
- mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command",\r
- "0.8.0.v201108120515"),\r
- mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime",\r
- "0.8.0.v201108120515"),\r
- mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell",\r
- "0.8.0.v201110170705"),\r
- // List logger bundles\r
- mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),\r
- mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(),\r
- mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(),\r
- mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(),\r
- // List all the bundles on which the test case depends\r
- mavenBundle("org.opendaylight.controller",\r
+ //\r
+ systemProperty("logback.configurationFile").value(\r
+ "file:" + PathUtils.getBaseDir()\r
+ + "/src/test/resources/logback.xml"),\r
+ // To start OSGi console for inspection remotely\r
+ systemProperty("osgi.console").value("2401"),\r
+ // Set the systemPackages (used by clustering)\r
+ systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"),\r
+ // List framework bundles\r
+ mavenBundle("equinoxSDK381",\r
+ "org.eclipse.equinox.console").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.eclipse.equinox.util").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.eclipse.osgi.services").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.eclipse.equinox.ds").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.apache.felix.gogo.command").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.apache.felix.gogo.runtime").versionAsInProject(),\r
+ mavenBundle("equinoxSDK381",\r
+ "org.apache.felix.gogo.shell").versionAsInProject(),\r
+ // List logger bundles\r
+ mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),\r
+ mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(),\r
+ mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(),\r
+ mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(),\r
+ // List all the bundles on which the test case depends\r
+ mavenBundle("org.opendaylight.controller",\r
"clustering.services").versionAsInProject(),\r
- mavenBundle("org.opendaylight.controller",\r
+ mavenBundle("org.opendaylight.controller",\r
"clustering.services-implementation").versionAsInProject(),\r
- mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(),\r
- mavenBundle("org.opendaylight.controller",\r
+ mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(),\r
+ mavenBundle("org.opendaylight.controller",\r
"sal.implementation").versionAsInProject(),\r
- mavenBundle("org.jboss.spec.javax.transaction",\r
+ mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(),\r
+ mavenBundle("org.opendaylight.controller",\r
+ "containermanager.implementation").versionAsInProject(),\r
+ mavenBundle("org.jboss.spec.javax.transaction",\r
"jboss-transaction-api_1.1_spec").versionAsInProject(),\r
- mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),\r
- mavenBundle("org.apache.felix",\r
+ mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),\r
+ mavenBundle("org.apache.felix",\r
"org.apache.felix.dependencymanager").versionAsInProject(),\r
- junitBundles());\r
+ mavenBundle("org.apache.felix",\r
+ "org.apache.felix.dependencymanager.shell").versionAsInProject(),\r
+ junitBundles());\r
}\r
\r
private String stateToString(int state) {\r
int state = b[i].getState();\r
if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {\r
log.debug("Bundle:" + b[i].getSymbolicName() + " state:"\r
- + stateToString(state));\r
+ + stateToString(state));\r
debugit = true;\r
}\r
}\r
if (debugit) {\r
log.debug("Do some debugging because some bundle is "\r
- + "unresolved");\r
+ + "unresolved");\r
}\r
\r
// Assert if true, if false we are good to go!\r
assertFalse(debugit);\r
\r
- ServiceReference r = bc.getServiceReference(IClusterServices.class\r
- .getName());\r
- if (r != null) {\r
- this.clusterServices = (IClusterServices) bc.getService(r);\r
- }\r
+ this.clusterServices = (IClusterServices)ServiceHelper\r
+ .getGlobalInstance(IClusterServices.class, this);\r
assertNotNull(this.clusterServices);\r
\r
+ this.clusterDefaultServices = (IClusterContainerServices)ServiceHelper\r
+ .getInstance(IClusterContainerServices.class, "default", this);\r
+ assertNotNull(this.clusterDefaultServices);\r
+\r
+ this.clusterGlobalServices = (IClusterGlobalServices)ServiceHelper\r
+ .getGlobalInstance(IClusterGlobalServices.class, this);\r
+ assertNotNull(this.clusterGlobalServices);\r
}\r
\r
@Test\r
public void clusterTest() throws CacheExistException, CacheConfigException,\r
- CacheListenerAddException {\r
+ CacheListenerAddException {\r
\r
String container1 = "Container1";\r
String container2 = "Container2";\r
}\r
\r
@Override\r
- public void entryUpdated(Integer key, String new_value,\r
+ public void entryUpdated(Integer key, String newValue,\r
String containerName, String cacheName, boolean originLocal) {\r
return;\r
}\r
return;\r
}\r
}\r
+\r
+ @Test\r
+ public void clusterContainerAndGlobalTest() throws CacheExistException, CacheConfigException,\r
+ CacheListenerAddException, InterruptedException {\r
+ String cache1 = "Cache1";\r
+ String cache2 = "Cache2";\r
+ // Lets test the case of caches with same name in different\r
+ // containers (actually global an container case)\r
+ String cache3 = "Cache2";\r
+\r
+ HashSet<cacheMode> cacheModeSet = new HashSet<cacheMode>();\r
+ cacheModeSet.add(cacheMode.NON_TRANSACTIONAL);\r
+ ConcurrentMap cm11 = this.clusterDefaultServices.createCache(cache1, cacheModeSet);\r
+ assertNotNull(cm11);\r
+\r
+ assertTrue(this.clusterDefaultServices.existCache(cache1));\r
+ assertEquals(cm11, this.clusterDefaultServices.getCache(cache1));\r
+\r
+ ConcurrentMap cm12 = this.clusterDefaultServices.createCache(cache2, cacheModeSet);\r
+ ConcurrentMap cm23 = this.clusterGlobalServices.createCache(cache3, cacheModeSet);\r
+\r
+ // Now given cahe2 and cache3 have same name lets make sure\r
+ // they don't return the same reference\r
+ assertNotNull(this.clusterGlobalServices.getCache(cache2));\r
+ // cm12 reference must be different than cm23\r
+ assertTrue(cm12 != cm23);\r
+\r
+ HashSet<String> cacheList = (HashSet<String>) this.clusterDefaultServices\r
+ .getCacheList();\r
+ assertEquals(2, cacheList.size());\r
+ assertTrue(cacheList.contains(cache1));\r
+ assertTrue(cacheList.contains(cache2));\r
+\r
+ assertNotNull(this.clusterDefaultServices.getCacheProperties(cache1));\r
+\r
+ {\r
+ /***********************************/\r
+ /* Testing cacheAware in Container */\r
+ /***********************************/\r
+ Dictionary<String, Object> props = new Hashtable<String, Object>();\r
+ Set<String> propSet = new HashSet<String>();\r
+ propSet.add(cache1);\r
+ propSet.add(cache2);\r
+ props.put("cachenames", propSet);\r
+ CacheAware listener = new CacheAware();\r
+ CacheAware listenerRepeated = new CacheAware();\r
+ ServiceRegistration updateServiceReg = ServiceHelper.registerServiceWReg(ICacheUpdateAware.class, "default",\r
+ listener, props);\r
+ assertNotNull(updateServiceReg);\r
+\r
+ // Register another service for the same caches, this\r
+ // should not get any update because we don't allow to\r
+ // override the existing unless before unregistered\r
+ ServiceRegistration updateServiceRegRepeated = ServiceHelper.registerServiceWReg(ICacheUpdateAware.class,\r
+ "default",\r
+ listenerRepeated, props);\r
+ assertNotNull(updateServiceRegRepeated);\r
+ CountDownLatch res = null;\r
+ List<Update> ups = null;\r
+ Update up = null;\r
+ Integer k1 = new Integer(10);\r
+ Long k2 = new Long(100L);\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(2);\r
+ // modify the cache\r
+ cm11.put(k1, "foo");\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 2);\r
+ // Validate that first we get an update (yes even in case of a\r
+ // new value added)\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertTrue(up.value.equals("foo"));\r
+ assertTrue(up.cacheName.equals(cache1));\r
+ // Validate that we then get a create\r
+ up = ups.get(1);\r
+ assertTrue(up.t.equals(UpdateType.ADDED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache1));\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm11.put(k1, "baz");\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get an update with expect fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertTrue(up.value.equals("baz"));\r
+ assertTrue(up.cacheName.equals(cache1));\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm11.remove(k1);\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get a delete with expected fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.REMOVED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache1));\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(2);\r
+ // modify the cache\r
+ cm12.put(k2, new Short((short)15));\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 2);\r
+ // Validate that first we get an update (yes even in case of a\r
+ // new value added)\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k2));\r
+ assertTrue(up.value.equals(new Short((short)15)));\r
+ assertTrue(up.cacheName.equals(cache2));\r
+ // Validate that we then get a create\r
+ up = ups.get(1);\r
+ assertTrue(up.t.equals(UpdateType.ADDED));\r
+ assertTrue(up.key.equals(k2));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache2));\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm12.put(k2, "BAZ");\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get an update with expect fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k2));\r
+ assertTrue(up.value.equals("BAZ"));\r
+ assertTrue(up.cacheName.equals(cache2));\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm12.remove(k2);\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get a delete with expected fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.REMOVED));\r
+ assertTrue(up.key.equals(k2));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache2));\r
+\r
+ /******************************************************************/\r
+ /* NOW LETS REMOVE THE REGISTRATION AND MAKE SURE NO UPDATS COMES */\r
+ /******************************************************************/\r
+ updateServiceReg.unregister();\r
+ // Start monitoring the updates, noone should come in\r
+ res = listener.restart(1);\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // modify the cache\r
+ cm11.put(k1, "foo");\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // modify the cache\r
+ cm11.put(k1, "baz");\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // modify the cache\r
+ cm11.remove(k1);\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // modify the cache\r
+ cm12.put(k2, new Short((short)15));\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // modify the cache\r
+ cm12.put(k2, "BAZ");\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // modify the cache\r
+ cm12.remove(k2);\r
+\r
+\r
+ // Wait to make sure no updates came in, clearly this is\r
+ // error prone as logic, but cannot find a better way than\r
+ // this to make sure updates didn't get in\r
+ res.await(1L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 0);\r
+ }\r
+\r
+ {\r
+ /***********************************/\r
+ /* Testing cacheAware in Global */\r
+ /***********************************/\r
+ Dictionary<String, Object> props = new Hashtable<String, Object>();\r
+ Set<String> propSet = new HashSet<String>();\r
+ propSet.add(cache3);\r
+ props.put("cachenames", propSet);\r
+ CacheAware listener = new CacheAware();\r
+ ServiceRegistration updateServiceReg = ServiceHelper.registerGlobalServiceWReg(ICacheUpdateAware.class,\r
+ listener, props);\r
+ assertNotNull(updateServiceReg);\r
+\r
+ CountDownLatch res = null;\r
+ List<Update> ups = null;\r
+ Update up = null;\r
+ Integer k1 = new Integer(10);\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(2);\r
+ // modify the cache\r
+ cm23.put(k1, "foo");\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 2);\r
+ // Validate that first we get an update (yes even in case of a\r
+ // new value added)\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertTrue(up.value.equals("foo"));\r
+ assertTrue(up.cacheName.equals(cache3));\r
+ // Validate that we then get a create\r
+ up = ups.get(1);\r
+ assertTrue(up.t.equals(UpdateType.ADDED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache3));\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm23.put(k1, "baz");\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get an update with expect fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.CHANGED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertTrue(up.value.equals("baz"));\r
+ assertTrue(up.cacheName.equals(cache3));\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // Start monitoring the updates\r
+ res = listener.restart(1);\r
+ // modify the cache\r
+ cm23.remove(k1);\r
+ // Wait\r
+ res.await(100L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 1);\r
+ // Validate we get a delete with expected fields\r
+ up = ups.get(0);\r
+ assertTrue(up.t.equals(UpdateType.REMOVED));\r
+ assertTrue(up.key.equals(k1));\r
+ assertNull(up.value);\r
+ assertTrue(up.cacheName.equals(cache3));\r
+\r
+ /******************************************************************/\r
+ /* NOW LETS REMOVE THE REGISTRATION AND MAKE SURE NO UPDATS COMES */\r
+ /******************************************************************/\r
+ updateServiceReg.unregister();\r
+ // Start monitoring the updates, noone should come in\r
+ res = listener.restart(1);\r
+\r
+ /***********************/\r
+ /* CREATE NEW KEY CASE */\r
+ /***********************/\r
+ // modify the cache\r
+ cm23.put(k1, "foo");\r
+\r
+ /*******************************/\r
+ /* UPDATE AN EXISTING KEY CASE */\r
+ /*******************************/\r
+ // modify the cache\r
+ cm23.put(k1, "baz");\r
+\r
+ /********************************/\r
+ /* REMOVAL OF EXISTING KEY CASE */\r
+ /********************************/\r
+ // modify the cache\r
+ cm23.remove(k1);\r
+\r
+ // Wait to make sure no updates came in, clearly this is\r
+ // error prone as logic, but cannot find a better way than\r
+ // this to make sure updates didn't get in\r
+ res.await(1L, TimeUnit.SECONDS);\r
+ // Analyze the updates\r
+ ups = listener.getUpdates();\r
+ assertTrue(ups.size() == 0);\r
+ }\r
+\r
+ InetAddress addr = this.clusterDefaultServices.getMyAddress();\r
+ assertNotNull(addr);\r
+\r
+ List<InetAddress> addrList = this.clusterDefaultServices\r
+ .getClusteredControllers();\r
+\r
+ this.clusterDefaultServices.destroyCache(cache1);\r
+ assertFalse(this.clusterDefaultServices.existCache(cache1));\r
+ }\r
+\r
+ private class Update {\r
+ Object key;\r
+ Object value;\r
+ String cacheName;\r
+ UpdateType t;\r
+\r
+ Update (UpdateType t, Object key, Object value, String cacheName) {\r
+ this.t = t;\r
+ this.key = key;\r
+ this.value = value;\r
+ this.cacheName = cacheName;\r
+ }\r
+ }\r
+\r
+ private class CacheAware implements ICacheUpdateAware {\r
+ private CopyOnWriteArrayList<Update> gotUpdates;\r
+ private CountDownLatch latch = null;\r
+\r
+ CacheAware() {\r
+ this.gotUpdates = new CopyOnWriteArrayList<Update>();\r
+ }\r
+\r
+\r
+ /**\r
+ * Restart the monitor of the updates on the CacheAware object\r
+ *\r
+ * @param expectedOperations Number of expected updates\r
+ *\r
+ * @return a countdown latch which will be used to wait till the updates are done\r
+ */\r
+ CountDownLatch restart(int expectedOperations) {\r
+ this.gotUpdates.clear();\r
+ this.latch = new CountDownLatch(expectedOperations);\r
+ return this.latch;\r
+ }\r
+\r
+ List<Update> getUpdates() {\r
+ return this.gotUpdates;\r
+ }\r
+\r
+ @Override\r
+ public void entryCreated(Object key, String cacheName, boolean originLocal) {\r
+ log.debug("CACHE[{}] Got an entry created for key:{}", cacheName, key);\r
+ Update u = new Update(UpdateType.ADDED, key, null, cacheName);\r
+ this.gotUpdates.add(u);\r
+ this.latch.countDown();\r
+ }\r
+\r
+ @Override\r
+ public void entryUpdated(Object key, Object newValue, String cacheName, boolean originLocal) {\r
+ log.debug("CACHE[{}] Got an entry updated for key:{} newValue:{}", cacheName, key, newValue);\r
+ Update u = new Update(UpdateType.CHANGED, key, newValue, cacheName);\r
+ this.gotUpdates.add(u);\r
+ this.latch.countDown();\r
+ }\r
+\r
+ @Override\r
+ public void entryDeleted(Object key, String cacheName, boolean originLocal) {\r
+ log.debug("CACHE[{}] Got an entry delete for key:{}", cacheName, key);\r
+ Update u = new Update(UpdateType.REMOVED, key, null, cacheName);\r
+ this.gotUpdates.add(u);\r
+ this.latch.countDown();\r
+ }\r
+ }\r
}\r
*/
public void configureInstance(Component c, Object imp, String containerName) {
if (imp.equals(ClusterContainerManager.class)) {
- c.setInterface(new String[] { IClusterContainerServices.class
- .getName() }, null);
+ c.setInterface(new String[] { IClusterContainerServices.class.getName() },
+ null);
- c.add(createServiceDependency().setService(IClusterServices.class)
- .setCallbacks("setClusterService", "unsetClusterService")
- .setRequired(true));
+ c.add(createServiceDependency()
+ .setService(IClusterServices.class)
+ .setCallbacks("setClusterService", "unsetClusterService")
+ .setRequired(true));
// CacheUpdate services will be none or many so the
// dependency is optional
- c.add(createContainerServiceDependency(containerName).setService(
- ICacheUpdateAware.class).setCallbacks(
- "setCacheUpdateAware", "unsetCacheUpdateAware")
- .setRequired(false));
+ c.add(createContainerServiceDependency(containerName)
+ .setService(ICacheUpdateAware.class)
+ .setCallbacks("setCacheUpdateAware", "unsetCacheUpdateAware")
+ .setRequired(false));
// Coordinator change event can be one or many so
// dependency is optional
- c.add(createContainerServiceDependency(containerName).setService(
- ICoordinatorChangeAware.class).setCallbacks(
- "setCoordinatorChangeAware", "unsetCoordinatorChangeAware")
- .setRequired(false));
+ c.add(createContainerServiceDependency(containerName)
+ .setService(ICoordinatorChangeAware.class)
+ .setCallbacks("setCoordinatorChangeAware", "unsetCoordinatorChangeAware")
+ .setRequired(false));
}
}
public void configureGlobalInstance(Component c, Object imp) {
if (imp.equals(ClusterManager.class)) {
// export the service for Apps and Plugins
- c.setInterface(new String[] { IClusterServices.class.getName() },
- null);
+ c.setInterface(new String[] { IClusterServices.class.getName() }, null);
}
if (imp.equals(ClusterGlobalManager.class)) {
- c.setInterface(new String[] { IClusterGlobalServices.class
- .getName() }, null);
+ c.setInterface(new String[] { IClusterGlobalServices.class.getName() }, null);
- c.add(createServiceDependency().setService(IClusterServices.class)
- .setCallbacks("setClusterService", "unsetClusterService")
- .setRequired(true));
+ c.add(createServiceDependency()
+ .setService(IClusterServices.class)
+ .setCallbacks("setClusterService", "unsetClusterService")
+ .setRequired(true));
// CacheUpdate services will be none or many so the
// dependency is optional
- c.add(createServiceDependency().setService(ICacheUpdateAware.class)
- .setCallbacks("setCacheUpdateAware",
- "unsetCacheUpdateAware").setRequired(false));
+ c.add(createServiceDependency()
+ .setService(ICacheUpdateAware.class)
+ .setCallbacks("setCacheUpdateAware", "unsetCacheUpdateAware")
+ .setRequired(false));
// Coordinator change event can be one or many so
// dependency is optional
- c.add(createServiceDependency().setService(
- ICoordinatorChangeAware.class).setCallbacks(
- "setCoordinatorChangeAware", "unsetCoordinatorChangeAware")
- .setRequired(false));
+ c.add(createServiceDependency()
+ .setService(ICoordinatorChangeAware.class)
+ .setCallbacks("setCoordinatorChangeAware", "unsetCoordinatorChangeAware")
+ .setRequired(false));
}
}
}
package org.opendaylight.controller.clustering.services_implementation.internal;
+import java.util.Map;
+import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-public class ClusterGlobalManager extends ClusterManagerCommon implements
- IClusterGlobalServices {
+public class ClusterGlobalManager
+ extends ClusterManagerCommon
+ implements IClusterGlobalServices {
+ protected static final Logger logger = LoggerFactory.getLogger(ClusterGlobalManager.class);
+
+ @Override
+ void setCacheUpdateAware(Map props, ICacheUpdateAware s) {
+ logger.trace("setCacheUpdateAware");
+ if (props.get("containerName") != null) {
+ // If we got a reference with the containerName property
+ // that is not what we are looking for, so filter it out.
+ return;
+ }
+ super.setCacheUpdateAware(props, s);
+ }
+
+ @Override
+ void unsetCacheUpdateAware(Map props, ICacheUpdateAware s) {
+ logger.trace("unsetCacheUpdateAware");
+ if (props.get("containerName") != null) {
+ // If we got a reference with the containerName property
+ // that is not what we are looking for, so filter it out.
+ return;
+ }
+ super.unsetCacheUpdateAware(props, s);
+ }
}
package org.opendaylight.controller.clustering.services_implementation.internal;
import java.net.InetAddress;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-
+import org.apache.felix.dm.Component;
import org.opendaylight.controller.clustering.services.CacheConfigException;
import org.opendaylight.controller.clustering.services.CacheExistException;
import org.opendaylight.controller.clustering.services.CacheListenerAddException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Dictionary;
-import java.util.Collections;
-import java.util.HashSet;
-import org.apache.felix.dm.Component;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
abstract public class ClusterManagerCommon implements IClusterServicesCommon {
protected String containerName = null;
private IClusterServices clusterService = null;
protected static final Logger logger = LoggerFactory
.getLogger(ClusterManagerCommon.class);
- private Set<ICacheUpdateAware> cacheUpdateAware = Collections
- .synchronizedSet(new HashSet<ICacheUpdateAware>());
+ private ConcurrentMap<String, GetUpdatesContainer> cacheUpdateAware =
+ new ConcurrentHashMap<String, GetUpdatesContainer>();
private Set<ICoordinatorChangeAware> coordinatorChangeAware = Collections
.synchronizedSet(new HashSet<ICoordinatorChangeAware>());
private ListenCoordinatorChange coordinatorChangeListener = null;
}
}
- void setCacheUpdateAware(ICacheUpdateAware s) {
+ void setCacheUpdateAware(Map props, ICacheUpdateAware s) {
+ logger.trace("CacheUpdateAware being set on container:{}",
+ this.containerName);
if (this.cacheUpdateAware != null) {
- this.cacheUpdateAware.add(s);
+ Set<String> caches = (Set<String>)props.get("cachenames");
+ if (caches != null) {
+ logger.trace("cachenames provided below:");
+ for (String cache : caches) {
+ if (this.cacheUpdateAware.get(cache) != null) {
+ logger.error("cachename:{} on container:{} has " +
+ "already a listener", cache,
+ this.containerName);
+ } else {
+ GetUpdatesContainer<?, ?> up =
+ new GetUpdatesContainer(s, this.containerName,
+ cache);
+ if (up != null) {
+ try {
+ this.clusterService.addListener(this.containerName,
+ cache, up);
+ this.cacheUpdateAware.put(cache, up);
+ logger.trace("cachename:{} on container:{} has " +
+ "been registered", cache,
+ this.containerName);
+ } catch (CacheListenerAddException exc) {
+ // Do nothing, the important is that
+ // we don't register the listener in
+ // the shadow, and we are not doing
+ // that.
+ }
+ }
+ }
+ }
+ }
}
}
- void unsetCacheUpdateAware(ICacheUpdateAware s) {
+ void unsetCacheUpdateAware(Map props, ICacheUpdateAware s) {
+ logger.trace("CacheUpdateAware being unset on container:{}",
+ this.containerName);
if (this.cacheUpdateAware != null) {
- this.cacheUpdateAware.remove(s);
+ Set<String> caches = (Set<String>)props.get("cachenames");
+ if (caches != null) {
+ logger.trace("cachenames provided below:");
+ GetUpdatesContainer<?, ?> up = null;
+ for (String cache : caches) {
+ up = this.cacheUpdateAware.get(cache);
+ if (up != null) {
+ this.cacheUpdateAware.remove(cache);
+ this.clusterService.removeListener(this.containerName,
+ cache, up);
+ }
+ }
+ }
}
}
--- /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.clustering.services_implementation.internal;
+
+import org.opendaylight.controller.clustering.services.IGetUpdates;
+import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
+
+public class GetUpdatesContainer<K,V> implements IGetUpdates<K,V> {
+ private ICacheUpdateAware<K,V> toBeUpdated;
+ private String containerName;
+ private String cacheName;
+
+ public GetUpdatesContainer(ICacheUpdateAware<K,V> i, String containerName,
+ String cacheName) {
+ this.toBeUpdated = i;
+ this.containerName = containerName;
+ this.cacheName = cacheName;
+ }
+
+ public ICacheUpdateAware<K,V> whichListener() {
+ return this.toBeUpdated;
+ }
+
+ @Override
+ public void entryCreated(K key, String containerName, String cacheName,
+ boolean local) {
+ if (this.toBeUpdated != null) {
+ this.toBeUpdated.entryCreated(key, cacheName, local);
+ }
+ }
+
+ @Override
+ public void entryUpdated(K key, V new_value, String containerName,
+ String cacheName,
+ boolean local) {
+ if (this.toBeUpdated != null) {
+ this.toBeUpdated.entryUpdated(key, new_value, cacheName, local);
+ }
+ }
+
+ @Override
+ public void entryDeleted(K key, String containerName, String cacheName,
+ boolean local) {
+ if (this.toBeUpdated != null) {
+ this.toBeUpdated.entryDeleted(key, cacheName, local);
+ }
+ }
+}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
- activate="start"
- deactivate="stop"
- immediate="true"
- name="org.opendaylight.controller.clustering.services_implementation.internal.ClusterManager">
- <implementation class="org.opendaylight.controller.clustering.services_implementation.internal.ClusterManager"/>
- <service>
- <provide interface="org.opendaylight.controller.clustering.services.IClusterServices"/>
- </service>
-</scr:component>
--- /dev/null
+<configuration scan="true">
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+ </pattern>
+ </encoder>
+ </appender>
+
+ <root level="error">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
*/
public IEntityClass getEntityClass();
+ public boolean isStaticHost();
+
+ public void setStaticHost(boolean isStatic);
+
public HostNodeConnector toHostNodeConnector();
}
protected final Short[] vlanIds;
protected volatile String dhcpClientName;
+ private boolean staticHost;
+
/**
* These are the old attachment points for the device that were valid no
* more than INACTIVITY_TIME ago.
byte[] macAddr = macLongToByte(this.getMACAddress());
HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n,
(short) 0);
+ nc.setStaticHost(this.isStaticHost());
return nc;
} catch (Exception e) {
return null;
return macAddr;
}
+ public boolean isStaticHost(){
+ return this.staticHost;
+ }
+
+ public void setStaticHost(boolean isStatic){
+ this.staticHost = isStatic;
+ }
+
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.DELETE;
import java.net.InetAddress;
+import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import org.opendaylight.controller.hosttracker.IfNewHostNotify;
import org.opendaylight.controller.hosttracker.SwitchPort;
import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.ConstructionException;
import org.opendaylight.controller.sal.core.Edge;
+import org.opendaylight.controller.sal.core.Host;
+import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.controller.sal.core.Tier;
+import org.opendaylight.controller.sal.core.UpdateType;
import org.opendaylight.controller.sal.packet.ARP;
import org.opendaylight.controller.sal.packet.Ethernet;
import org.opendaylight.controller.sal.packet.IDataPacketService;
import org.opendaylight.controller.sal.packet.Packet;
import org.opendaylight.controller.sal.packet.PacketResult;
import org.opendaylight.controller.sal.packet.RawPacket;
+import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
+import org.opendaylight.controller.sal.packet.address.EthernetAddress;
import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
+import org.opendaylight.controller.sal.utils.HexEncode;
import org.opendaylight.controller.sal.utils.ListenerDispatcher;
import org.opendaylight.controller.sal.utils.MultiIterator;
+import org.opendaylight.controller.sal.utils.NetUtils;
import org.opendaylight.controller.sal.utils.SingletonTask;
import org.opendaylight.controller.sal.utils.Status;
+import org.opendaylight.controller.sal.utils.StatusCode;
import org.opendaylight.controller.switchmanager.ISwitchManager;
import org.opendaylight.controller.topologymanager.ITopologyManager;
import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
logger.info("Primary index {}", primaryIndex);
ArrayList<Long> deleteQueue = null;
LinkedList<DeviceUpdate> deviceUpdates = null;
+ Device oldDevice = null;
Device device = null;
// we may need to restart the learning process if we detect
// modified this Device).
if (!res)
continue;
-
+ oldDevice = device;
device = newDevice;
// update indices
if (!updateIndices(device, deviceKey)) {
if (moved) {
// we count device moved events in
// sendDeviceMovedNotification()
- sendDeviceMovedNotification(device);
+ sendDeviceMovedNotification(device, oldDevice);
if (logger.isTraceEnabled()) {
logger.trace("Device moved: attachment points {},"
+ "entities {}", device.attachmentPoints,
protected void notifyListeners(List<IDeviceListener> listeners,
DeviceUpdate update) {
+ // Topology update is for some reason outside of listeners registry
+ // logic
+ Entity[] ents = update.device.getEntities();
+ Entity e = ents[ents.length-1];
+ NodeConnector p = e.getPort();
+ Node node = p.getNode();
+ Host h = null;
+ try {
+ byte[] mac = NetUtils.longToByteArray6(e.getMacAddress());
+ DataLinkAddress dla = new EthernetAddress(
+ mac);
+ e.getIpv4Address();
+ InetAddress.getAllByName(e.getIpv4Address().toString());
+ h = new org.opendaylight.controller.sal.core.Host(dla,
+ InetAddress.getByName(e.getIpv4Address().toString()));
+ } catch (ConstructionException ce) {
+ p = null;
+ h = null;
+ } catch (UnknownHostException ue){
+ p = null;
+ h = null;
+ }
+
+ if (topology != null && p != null && h != null) {
+ if (update.change.equals(DeviceUpdate.Change.ADD)) {
+ Tier tier = new Tier(1);
+ switchManager.setNodeProp(node, tier);
+ topology.updateHostLink(p, h, UpdateType.ADDED, null);
+ } else {
+ // No need to reset the tiering if no other hosts are currently
+ // connected
+ // If this switch was discovered to be an access switch, it
+ // still is even if the host is down
+ Tier tier = new Tier(0);
+ switchManager.setNodeProp(node, tier);
+ topology.updateHostLink(p, h, UpdateType.REMOVED, null);
+ }
+ }
+
if (listeners == null && newHostNotify.isEmpty()) {
return;
}
case ADD:
notify.notifyHTClient(update.device.toHostNodeConnector());
break;
+ case DELETE:
+ notify.notifyHTClientHostRemoved(update.device.toHostNodeConnector());
+ break;
+ case CHANGE:
}
}
}
}
}
+ /**
+ * Send update notifications to listeners.
+ * IfNewHostNotify listeners need to remove old device and add new device.
+ * @param device
+ * @param oldDevice
+ */
+ protected void sendDeviceMovedNotification(Device device, Device oldDevice){
+ for (IfNewHostNotify notify : newHostNotify){
+ notify.notifyHTClientHostRemoved(oldDevice.toHostNodeConnector());
+ notify.notifyHTClient(device.toHostNodeConnector());
+ }
+ sendDeviceMovedNotification(device);
+ }
/**
* this method will reclassify and reconcile a device - possibilities are -
@Override
public Set<HostNodeConnector> getActiveStaticHosts() {
- // TODO Auto-generated method stub
- return null;
+ Collection<Device> devices = Collections
+ .unmodifiableCollection(deviceMap.values());
+ Iterator<Device> i = devices.iterator();
+ Set<HostNodeConnector> nc = new HashSet<HostNodeConnector>();
+ while (i.hasNext()) {
+ Device device = i.next();
+ if(device.isStaticHost())
+ nc.add(device.toHostNodeConnector());
+ }
+ return nc;
}
@Override
@Override
public Status addStaticHost(String networkAddress, String dataLayerAddress,
NodeConnector nc, String vlan) {
- // TODO Auto-generated method stub
- return null;
+ Long mac = HexEncode.stringToLong(dataLayerAddress);
+ try{
+ InetAddress addr = InetAddress.getByName(networkAddress);
+ int ip = toIPv4Address(addr.getAddress());
+ Entity e = new Entity(mac, Short.valueOf(vlan), ip, nc, new Date());
+ Device d = this.learnDeviceByEntity(e);
+ d.setStaticHost(true);
+ return new Status(StatusCode.SUCCESS);
+ }catch(UnknownHostException e){
+ return new Status(StatusCode.INTERNALERROR);
+ }
}
@Override
public Status removeStaticHost(String networkAddress) {
- // TODO Auto-generated method stub
- return null;
+ Integer addr;
+ try {
+ addr = toIPv4Address(InetAddress.getByName(networkAddress).getAddress());
+ } catch (UnknownHostException e) {
+ return new Status(StatusCode.NOTFOUND, "Host does not exist");
+ }
+ Iterator<Device> di = this.getDeviceIteratorForQuery(null, null, addr, null);
+ List<IDeviceListener> listeners = deviceListeners
+ .getOrderedListeners();
+ while(di.hasNext()){
+ Device d = di.next();
+ if(d.isStaticHost()){
+ deleteDevice(d);
+ for (IfNewHostNotify notify : newHostNotify)
+ notify.notifyHTClientHostRemoved(d.toHostNodeConnector());
+ for (IDeviceListener listener : listeners)
+ listener.deviceRemoved(d);
+ }
+ }
+ return new Status(StatusCode.SUCCESS);
}
/**
package org.opendaylight.controller.sal.authorization;
+import java.io.Serializable;
+
/**
* It represents the group/resource access privilege
*/
-public enum Privilege {
+public enum Privilege implements Serializable {
NONE(""), // no privilege
READ("r"), // read only
USE("u"), // use
Match reverse = this.clone();
// Flip symmetric fields
- for (Map.Entry<MatchType, MatchType> entry : Match.reversableMatches
- .entrySet()) {
+ for (Map.Entry<MatchType, MatchType> entry : Match.reversableMatches.entrySet()) {
MatchType from = entry.getKey();
MatchType to = entry.getValue();
if (this.isPresent(from)) {
- reverse.setField(to, this.getField(from).getValue(), this
- .getField(from).getMask());
+ reverse.setField(to, this.getField(from).getValue(), this.getField(from).getMask());
+ if (!this.isPresent(to)) {
+ reverse.clearField(from);
+ }
}
}
// Now adding the rest of the bits if any
if (extranumBits != 0) {
if (extranumBits < (NetUtils.NumBitsInAByte - extraOffsetBits)) {
- valfromnext = (byte) (data[startByteOffset + i + 1] & ((getMSBMask(extranumBits)) >> extraOffsetBits));
+ valfromnext = (byte) (data[startByteOffset + i] & ((getMSBMask(extranumBits)) >> extraOffsetBits));
bytes[i] = (byte) (valfromnext << extraOffsetBits);
} else if (extranumBits == (NetUtils.NumBitsInAByte - extraOffsetBits)) {
valfromcurr = (data[startByteOffset + i])
etherTypeClassMap.put(EtherTypes.ARP.shortValue(), ARP.class);
etherTypeClassMap.put(EtherTypes.IPv4.shortValue(), IPv4.class);
etherTypeClassMap.put(EtherTypes.LLDP.shortValue(), LLDP.class);
+ etherTypeClassMap.put(EtherTypes.VLANTAGGED.shortValue(), IEEE8021Q.class);
+ etherTypeClassMap.put(EtherTypes.OLDQINQ.shortValue(), IEEE8021Q.class);
+ etherTypeClassMap.put(EtherTypes.QINQ.shortValue(), IEEE8021Q.class);
+ etherTypeClassMap.put(EtherTypes.CISCOQINQ.shortValue(), IEEE8021Q.class);
}
private static Map<String, Pair<Integer, Integer>> fieldCoordinates = new LinkedHashMap<String, Pair<Integer, Integer>>() {
private static final long serialVersionUID = 1L;
--- /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.sal.packet;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+
+/**
+ * Class that represents the IEEE 802.1Q objects
+ */
+public class IEEE8021Q extends Packet {
+ private static final String PCP = "PriorityCodePoint";
+ private static final String CFI = "CanonicalFormatIndicator";
+ private static final String VID = "VlanIdentifier";
+ private static final String ETHT = "EtherType";
+
+ private static Map<String, Pair<Integer, Integer>> fieldCoordinates = new LinkedHashMap<String, Pair<Integer, Integer>>() {
+ private static final long serialVersionUID = 1L;
+ {
+ put(PCP, new ImmutablePair<Integer, Integer>(0, 3));
+ put(CFI, new ImmutablePair<Integer, Integer>(3, 1));
+ put(VID, new ImmutablePair<Integer, Integer>(4, 12));
+ put(ETHT, new ImmutablePair<Integer, Integer>(16, 16));
+ }
+ };
+ private final Map<String, byte[]> fieldValues;
+
+ /**
+ * Default constructor that creates and sets the HashMap
+ */
+ public IEEE8021Q() {
+ super();
+ fieldValues = new HashMap<String, byte[]>();
+ hdrFieldCoordMap = fieldCoordinates;
+ hdrFieldsMap = fieldValues;
+ }
+
+ /**
+ * Constructor that sets the access level for the packet and creates and
+ * sets the HashMap
+ */
+ public IEEE8021Q(boolean writeAccess) {
+ super(writeAccess);
+ fieldValues = new HashMap<String, byte[]>();
+ hdrFieldCoordMap = fieldCoordinates;
+ hdrFieldsMap = fieldValues;
+ }
+
+ @Override
+ /**
+ * Store the value read from data stream in hdrFieldMap
+ */
+ public void setHeaderField(String headerField, byte[] readValue) {
+ if (headerField.equals(ETHT)) {
+ payloadClass = Ethernet.etherTypeClassMap.get(BitBufferHelper.getShort(readValue));
+ }
+ hdrFieldsMap.put(headerField, readValue);
+ }
+
+ /**
+ * Gets the priority code point(PCP) stored
+ *
+ * @return byte - the PCP
+ */
+ public byte getPcp() {
+ return BitBufferHelper.getByte(fieldValues.get(PCP));
+ }
+
+ /**
+ * Gets the canonical format indicator(CFI) stored
+ *
+ * @return byte - the CFI
+ */
+ public byte getCfi() {
+ return BitBufferHelper.getByte(fieldValues.get(CFI));
+ }
+
+ /**
+ * Gets the VLAN identifier(VID) stored
+ *
+ * @return short - the VID
+ */
+ public short getVid() {
+ return BitBufferHelper.getShort(fieldValues.get(VID));
+ }
+
+ /**
+ * Gets the etherType stored
+ *
+ * @return short - the etherType
+ */
+ public short getEtherType() {
+ return BitBufferHelper.getShort(fieldValues.get(ETHT));
+ }
+
+ /**
+ * Sets the priority code point(PCP) for the current IEEE 802.1Q object
+ * instance
+ *
+ * @param byte - the PCP to set
+ */
+ public IEEE8021Q setPcp(byte pcp) {
+ byte[] priorityCodePoint = BitBufferHelper.toByteArray(pcp);
+ fieldValues.put(PCP, priorityCodePoint);
+ return this;
+ }
+
+ /**
+ * Sets the canonical format indicator(CFI) for the current IEEE 802.1Q
+ * object instance
+ *
+ * @param byte - the CFI to set
+ */
+ public IEEE8021Q setCfi(byte cfi) {
+ byte[] canonicalFormatIndicator = BitBufferHelper.toByteArray(cfi);
+ fieldValues.put(CFI, canonicalFormatIndicator);
+ return this;
+ }
+
+ /**
+ * Sets the VLAN identifier(VID) for the current IEEE 802.1Q instance
+ *
+ * @param short - the VID to set
+ */
+ public IEEE8021Q setVid(short vid) {
+ byte[] vlanIdentifier = BitBufferHelper.toByteArray(vid);
+ fieldValues.put(VID, vlanIdentifier);
+ return this;
+ }
+
+ /**
+ * Sets the etherType for the current IEEE 802.1Q object instance
+ *
+ * @param short - the etherType to set
+ */
+ public IEEE8021Q setEtherType(short etherType) {
+ byte[] ethType = BitBufferHelper.toByteArray(etherType);
+ fieldValues.put(ETHT, ethType);
+ return this;
+ }
+
+}
| (0xff & ba[2]) << 8 | (0xff & ba[3]);
}
+ /**
+ * Converts a long to 6 bytes array for mac addresses
+ * @param addr
+ * @return
+ */
+
+ public static byte[] longToByteArray6(long addr){
+ byte[] mac = new byte[6];
+ for(int i = 0; i < 6; i++){
+ mac[i] = (byte) (addr >> (i*8));
+ }
+ return mac;
+ }
+
+
/**
* Converts an integer number into a 4 bytes array
*
* @return true if registration happened, false otherwise
*/
public static boolean registerGlobalService(Class<?> clazz,
- Object instance, Dictionary<String, Object> properties) {
+ Object instance,
+ Dictionary<String, Object> properties) {
+ ServiceRegistration registration = registerGlobalServiceWReg(clazz, instance, properties);
+ if (registration == null) {
+ logger.error("Failed to register {} for instance {}", clazz, instance);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Register a Service in the OSGi service registry and return the ServiceRegistration
+ *
+ * @param clazz The target class
+ * @param containerName The container name
+ * @param instance of the object exporting the service, be careful
+ * the object must implement/extend clazz else the registration
+ * will fail unless a ServiceFactory is passed as parameter
+ * @param properties The properties to be attached to the service
+ * registration
+ * @return the ServiceRegistration if registration happened, null otherwise
+ */
+ public static ServiceRegistration registerServiceWReg(Class<?> clazz, String containerName,
+ Object instance, Dictionary<String, Object> properties) {
+ if (properties == null) {
+ properties = (Dictionary<String, Object>) new Hashtable<String, Object>();
+ }
+ properties.put("containerName", containerName);
+ return registerGlobalServiceWReg(clazz, instance, properties);
+ }
+
+ /**
+ * Register a Global Service in the OSGi service registry
+ *
+ * @param clazz The target class
+ * @param instance of the object exporting the service, be careful
+ * the object must implement/extend clazz else the registration
+ * will fail unless a ServiceFactory is passed as parameter
+ * @param properties The properties to be attached to the service
+ * registration
+ * @return the ServiceRegistration if registration happened, null otherwise
+ */
+ public static ServiceRegistration registerGlobalServiceWReg(Class<?> clazz,
+ Object instance,
+ Dictionary<String, Object> properties) {
try {
- BundleContext bCtx = FrameworkUtil.getBundle(instance.getClass())
- .getBundleContext();
+ BundleContext bCtx = FrameworkUtil.getBundle(instance.getClass()).getBundleContext();
if (bCtx == null) {
logger.error("Could not retrieve the BundleContext");
- return false;
+ return null;
}
- ServiceRegistration registration = bCtx.registerService(clazz
- .getName(), instance, properties);
- if (registration == null) {
- logger.error("Failed to register {} for instance {}", clazz,
- instance);
- }
- return true;
+ ServiceRegistration registration = bCtx.registerService(clazz.getName(), instance, properties);
+ return registration;
} catch (Exception e) {
logger.error("Exception {} while registering the service {}",
- e.getMessage(), instance.toString());
+ e.getMessage(), instance.toString());
}
- return false;
+ return null;
}
/**
--- /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.sal.packet;
+
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+public class IEEE8021QTest {
+
+ @Test
+ public void testGetPcp() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte pcp[] = { 5 };
+ vlan.hdrFieldsMap.put("PriorityCodePoint", pcp);
+ byte spcp = vlan.getPcp();
+ Assert.assertTrue(spcp == 5);
+ }
+
+ @Test
+ public void testGetCfi() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte cfi[] = { 0 };
+ vlan.hdrFieldsMap.put("CanonicalFormatIndicator", cfi);
+ byte scfi = vlan.getCfi();
+ Assert.assertTrue(scfi == 0);
+ }
+
+ @Test
+ public void testGetVid() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte vid[] = { (byte) 0xF, (byte) 0xFE }; // 4094
+ vlan.hdrFieldsMap.put("VlanIdentifier", vid);
+ short svid = vlan.getVid();
+ Assert.assertTrue(svid == 4094);
+ }
+
+ @Test
+ public void testGetEthertype() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte ethType[] = { 8, 6 };
+ vlan.hdrFieldsMap.put("EtherType", ethType);
+ short etherType = vlan.getEtherType();
+ Assert.assertTrue(etherType == 2054);
+ }
+
+ @Test
+ public void testSetPcp() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte pcp = 5;
+ vlan.setPcp(pcp);
+ byte[] bpcp = vlan.hdrFieldsMap.get("PriorityCodePoint");
+ Assert.assertTrue(bpcp[0] == 5);
+ }
+
+ @Test
+ public void testSetCfi() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ byte cfi = 0;
+ vlan.setCfi(cfi);
+ byte[] bcfi = vlan.hdrFieldsMap.get("CanonicalFormatIndicator");
+ Assert.assertTrue(bcfi[0] == 0);
+ }
+
+ @Test
+ public void testSetVid() throws Exception {
+ IEEE8021Q vlan = new IEEE8021Q();
+ short vid = 4094; // 0xFFE
+ vlan.setVid(vid);
+ byte[] bvid = vlan.hdrFieldsMap.get("VlanIdentifier");
+ Assert.assertTrue(bvid[0] == (byte) 0xF);
+ Assert.assertTrue(bvid[1] == (byte) 0xFE);
+ }
+
+ @Test
+ public void testSetEthertype() throws Exception {
+ Ethernet eth = new Ethernet();
+ short ethType = 2054; // 0x806
+ eth.setEtherType(ethType);
+ byte[] etherType = eth.hdrFieldsMap.get("EtherType");
+ Assert.assertTrue(etherType[0] == 8);
+ Assert.assertTrue(etherType[1] == 6);
+ }
+
+ @Test
+ public void testDeserialize() throws Exception {
+ short startOffset, numBits;
+ Ethernet eth = new Ethernet();
+ byte[] data = {
+ (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45, // Destination MAC
+ (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Source MAC
+ (byte) 0x81, (byte) 0x00, // EtherType
+ (byte) 0xAF, (byte) 0xFE, // PCP, CFI, VLAN ID
+ 8, 6, // EtherType
+ 0, 1, // Hardware Type
+ 8, 0, // Protocol Type
+ 6, // Hardware Address Length
+ 4, // Protocol Address Length
+ 0, 1, // opCode
+ (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Sender Hardware Address
+ (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1, // Sender Protocol Address
+ (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, // Target Hardware Address
+ (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE }; // Target Protocol Address
+
+ startOffset = 0;
+ numBits = (short) (data.length * 8);
+ eth.deserialize(data, startOffset, numBits);
+
+ short etherType = eth.getEtherType();
+ Assert.assertTrue(NetUtils.getUnsignedShort(etherType) == 0x8100);
+
+ IEEE8021Q vlanPacket = (IEEE8021Q) eth.getPayload();
+ Assert.assertTrue(vlanPacket.getCfi() == 0);
+ Assert.assertTrue(vlanPacket.getPcp() == 5);
+ Assert.assertTrue(vlanPacket.getVid() == 4094);
+ Assert.assertTrue(vlanPacket.getEtherType() == 2054); // 0x806
+
+ Packet arpPkt = (vlanPacket).getPayload();
+ Assert.assertTrue(arpPkt instanceof ARP);
+ }
+
+ @Test
+ public void testSerialize() throws Exception {
+ Ethernet eth = new Ethernet();
+
+ byte[] dMac = { (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45 };
+ byte[] sMac = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F };
+ eth.setDestinationMACAddress(dMac);
+ eth.setSourceMACAddress(sMac);
+ eth.setEtherType((short) 33024);
+
+ IEEE8021Q vlan = new IEEE8021Q();
+ vlan.setCfi((byte) 0x0);
+ vlan.setPcp((byte) 0x5);
+ vlan.setVid((short) 4094);
+ vlan.setEtherType((short) 2054);
+
+ vlan.setParent(eth);
+ eth.setPayload(vlan);
+
+ ARP arp = new ARP();
+ arp.setHardwareType((short) 1);
+ arp.setProtocolType((short) 2048);
+ arp.setHardwareAddressLength((byte) 0x6);
+ arp.setProtocolAddressLength((byte) 0x4);
+ arp.setOpCode((byte) 0x1);
+
+ byte[] senderHardwareAddress = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F };
+ byte[] senderProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1 };
+ byte[] targetProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE };
+ byte[] targetHardwareAddress = { (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 };
+ arp.setSenderHardwareAddress(senderHardwareAddress);
+ arp.setSenderProtocolAddress(senderProtocolAddress);
+ arp.setTargetHardwareAddress(targetHardwareAddress);
+ arp.setTargetProtocolAddress(targetProtocolAddress);
+
+ arp.setParent(vlan);
+ vlan.setPayload(arp);
+
+ byte[] data = eth.serialize();
+
+ Assert.assertTrue(data[0] == (byte) 0x0A); // Destination MAC
+ Assert.assertTrue(data[1] == (byte) 0x0C);
+ Assert.assertTrue(data[2] == (byte) 0x0E);
+ Assert.assertTrue(data[3] == (byte) 0x14);
+ Assert.assertTrue(data[4] == (byte) 0x37);
+ Assert.assertTrue(data[5] == (byte) 0x45);
+ Assert.assertTrue(data[6] == (byte) 0xA6); // Source MAC
+ Assert.assertTrue(data[7] == (byte) 0xEC);
+ Assert.assertTrue(data[8] == (byte) 0x9C);
+ Assert.assertTrue(data[9] == (byte) 0xAE);
+ Assert.assertTrue(data[10] == (byte) 0xB2);
+ Assert.assertTrue(data[11] == (byte) 0x9F);
+ Assert.assertTrue(data[12] == (byte) 0x81); // EtherType
+ Assert.assertTrue(data[13] == (byte) 0x00);
+ Assert.assertTrue(data[14] == (byte) 0xAF); // PCP, CFI, VLAN ID
+ Assert.assertTrue(data[15] == (byte) 0xFE);
+ Assert.assertTrue(data[16] == (byte) 0x08); // EtherType
+ Assert.assertTrue(data[17] == (byte) 0x06);
+ Assert.assertTrue(data[18] == (byte) 0x00); // Hardware Type
+ Assert.assertTrue(data[19] == (byte) 0x01);
+ Assert.assertTrue(data[20] == (byte) 0x08); // Protocol Type
+ Assert.assertTrue(data[21] == (byte) 0x0);
+ Assert.assertTrue(data[22] == (byte) 0x6); // Hardware Address Length
+ Assert.assertTrue(data[23] == (byte) 0x4); // Protocol Address Length
+ Assert.assertTrue(data[24] == (byte) 0x0); // opCode
+ Assert.assertTrue(data[25] == (byte) 0x1); // opCode
+ Assert.assertTrue(data[26] == (byte) 0xA6); // Source MAC
+ Assert.assertTrue(data[27] == (byte) 0xEC);
+ Assert.assertTrue(data[28] == (byte) 0x9C);
+ Assert.assertTrue(data[29] == (byte) 0xAE);
+ Assert.assertTrue(data[30] == (byte) 0xB2);
+ Assert.assertTrue(data[31] == (byte) 0x9F);
+ Assert.assertTrue(data[32] == (byte) 0x09); // Sender Protocol Address
+ Assert.assertTrue(data[33] == (byte) 0x09);
+ Assert.assertTrue(data[34] == (byte) 0x09);
+ Assert.assertTrue(data[35] == (byte) 0x01); // Target Hardware Address
+ Assert.assertTrue(data[36] == (byte) 0x00);
+ Assert.assertTrue(data[37] == (byte) 0x00);
+ Assert.assertTrue(data[38] == (byte) 0x00);
+ Assert.assertTrue(data[39] == (byte) 0x00);
+ Assert.assertTrue(data[40] == (byte) 0x00);
+ Assert.assertTrue(data[41] == (byte) 0x00);
+ Assert.assertTrue(data[42] == (byte) 0x09); // Target Protocol Address
+ Assert.assertTrue(data[43] == (byte) 0x09);
+ Assert.assertTrue(data[44] == (byte) 0x09);
+ Assert.assertTrue(data[45] == (byte) 0xFE);
+ }
+}
final Type rpcRes = Types.parameterizedTypeFor(
Types.typeForClass(RpcResult.class), outTypeInstance);
- method.addReturnType(Types.parameterizedTypeFor(future, rpcRes));
+ method.setReturnType(Types.parameterizedTypeFor(future, rpcRes));
for (DataNodeIterator it : rpcInOut) {
List<ContainerSchemaNode> nContainers = it.allContainers();
if ((nContainers != null) && !nContainers.isEmpty()) {
GeneratedTransferObject gto = new GeneratedTOBuilderImpl(
returnTypePkgName, returnTypeName).toInstance();
- newType.addExtendsType(gto);
+ newType.setExtendsType(gto);
} else {
- newType.addExtendsType(Types.getBaseIdentityTO());
+ newType.setExtendsType(Types.getBaseIdentityTO());
}
-
- return newType.toIdentityInstance();
+ newType.setAbstract(true);
+ return newType.toInstance();
}
private List<Type> allGroupingsToGenTypes(Module module) {
- final List<Type> genTypes = new ArrayList<Type>();
+ final List<Type> genTypes = new ArrayList<>();
final String basePackageName = moduleNamespaceToPackageName(module);
Set<GroupingDefinition> groupings = module.getGroupings();
if (groupings != null && !groupings.isEmpty()) {
.addProperty(parseToClassName(leafName));
propBuilder.setReadOnly(isReadOnly);
- propBuilder.addReturnType(returnType);
- propBuilder.addComment(leafDesc);
+ propBuilder.setReturnType(returnType);
+ propBuilder.setComment(leafDesc);
toBuilder.addEqualsIdentity(propBuilder);
toBuilder.addHashIdentity(propBuilder);
final MethodSignatureBuilder getMethod = interfaceBuilder
.addMethod(getterMethodName(schemaNodeName));
- getMethod.addComment(comment);
- getMethod.addReturnType(returnType);
+ getMethod.setComment(comment);
+ getMethod.setReturnType(returnType);
return getMethod;
}
final MethodSignatureBuilder setMethod = interfaceBuilder
.addMethod(setterMethodName(schemaNodeName));
- setMethod.addComment(comment);
+ setMethod.setComment(comment);
setMethod.addParameter(parameterType,
parseToValidParamName(schemaNodeName));
- setMethod.addReturnType(Types.voidType());
+ setMethod.setReturnType(Types.voidType());
return setMethod;
}
import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.controller.yang.common.QName;
import org.opendaylight.controller.yang.model.api.*;
-import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.*;
+import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
-import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
import org.opendaylight.controller.yang.model.util.ExtendedType;
import java.util.HashMap;
public void putReferencedType(final SchemaPath refTypePath,
final Type refType) {
if (refTypePath == null) {
- throw new IllegalArgumentException("Path reference of " +
- "Enumeration Type Definition cannot be NULL!");
+ throw new IllegalArgumentException("Path reference of "
+ + "Enumeration Type Definition cannot be NULL!");
}
if (refType == null) {
- throw new IllegalArgumentException("Reference to Enumeration " +
- "Type cannot be NULL!");
+ throw new IllegalArgumentException("Reference to Enumeration "
+ + "Type cannot be NULL!");
}
referencedTypes.put(refTypePath, refType);
}
final TypeDefinition<?> typeDefinition) {
Type returnType = null;
if (typeDefinition == null) {
- throw new IllegalArgumentException("Type Definition cannot be " +
- "NULL!");
+ throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have " +
- "non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
if (typeDefinition.getQName().getLocalName() == null) {
- throw new IllegalArgumentException("Type Definitions Local Name " +
- "cannot be NULL!");
+ throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
}
final String typedefName = typeDefinition.getQName().getLocalName();
if (typeDefinition instanceof ExtendedType) {
final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
returnType = provideTypeForLeafref(leafref);
} else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
- final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+ final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) baseTypeDef;
returnType = returnTypeForIdentityref(idref);
} else if (baseTypeDef instanceof EnumTypeDefinition) {
final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
returnType = resolveEnumFromTypeDefinition(enumTypeDef,
typedefName);
} else {
- final Module module = findParentModuleForTypeDefinition(schemaContext,
- typeDefinition);
+ final Module module = findParentModuleForTypeDefinition(
+ schemaContext, typeDefinition);
if (module != null) {
final Map<String, Type> genTOs = genTypeDefsContextMap
.get(module.getName());
final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
returnType = provideTypeForLeafref(leafref);
} else if (typeDefinition instanceof IdentityrefTypeDefinition) {
- final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+ final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
returnType = returnTypeForIdentityref(idref);
} else {
returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
.javaTypeForSchemaDefinitionType(typeDefinition);
}
}
- //TODO: add throw exception when we will be able to resolve ALL yang
+ // TODO: add throw exception when we will be able to resolve ALL yang
// types!
-// if (returnType == null) {
-// throw new IllegalArgumentException("Type Provider can't resolve " +
-// "type for specified Type Definition " + typedefName);
-// }
+ // if (returnType == null) {
+ // throw new IllegalArgumentException("Type Provider can't resolve " +
+ // "type for specified Type Definition " + typedefName);
+ // }
return returnType;
}
-
+
private Type returnTypeForIdentityref(IdentityrefTypeDefinition idref) {
QName baseIdQName = idref.getIdentity();
Module module = schemaContext.findModuleByNamespace(baseIdQName.getNamespace());
IdentitySchemaNode identity = null;
- for(IdentitySchemaNode id : module.getIdentities()) {
- if(id.getQName().equals(baseIdQName)) {
+ for (IdentitySchemaNode id : module.getIdentities()) {
+ if (id.getQName().equals(baseIdQName)) {
identity = id;
}
}
- if(identity == null) {
+ if (identity == null) {
throw new IllegalArgumentException("Target identity '" + baseIdQName + "' do not exists");
}
final TypeDefinition<?> typeDefinition) {
Type returnType = null;
if (typeDefinition == null) {
- throw new IllegalArgumentException("Type Definition cannot be " +
- "NULL!");
+ throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have " +
- "non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException("Type Definitions Local Name " +
- "cannot be NULL!");
+ throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
}
final String typedefName = typeDefinition.getQName().getLocalName();
if (!(baseTypeDef instanceof LeafrefTypeDefinition)
&& !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
- final Module module = findParentModuleForTypeDefinition(schemaContext,
- typeDefinition);
+ final Module module = findParentModuleForTypeDefinition(
+ schemaContext, typeDefinition);
if (module != null) {
final Map<String, Type> genTOs = genTypeDefsContextMap
private TypeDefinition<?> baseTypeDefForExtendedType(
final TypeDefinition<?> extendTypeDef) {
if (extendTypeDef == null) {
- throw new IllegalArgumentException("Type Definiition reference " +
- "cannot be NULL!");
+ throw new IllegalArgumentException("Type Definiition reference cannot be NULL!");
}
final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
if (baseTypeDef instanceof ExtendedType) {
public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
Type returnType = null;
if (leafrefType == null) {
- throw new IllegalArgumentException("Leafref Type Definition " +
- "reference cannot be NULL!");
+ throw new IllegalArgumentException("Leafref Type Definition reference cannot be NULL!");
}
if (leafrefType.getPathStatement() == null) {
- throw new IllegalArgumentException("The Path Statement for " +
- "Leafref Type Definition cannot be NULL!");
+ throw new IllegalArgumentException("The Path Statement for Leafref Type Definition cannot be NULL!");
}
final RevisionAwareXPath xpath = leafrefType.getPathStatement();
if (strXPath.matches(".*//[.* | .*//].*")) {
returnType = Types.typeForClass(Object.class);
} else {
- final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
+ final Module module = findParentModuleForTypeDefinition(
+ schemaContext, leafrefType);
if (module != null) {
final DataSchemaNode dataNode;
if (xpath.isAbsolute()) {
dataNode = findDataSchemaNode(schemaContext, module,
xpath);
} else {
- dataNode = findDataSchemaNodeForRelativeXPath(schemaContext,
- module, leafrefType, xpath);
+ dataNode = findDataSchemaNodeForRelativeXPath(
+ schemaContext, module, leafrefType, xpath);
}
if (leafContainsEnumDefinition(dataNode)) {
returnType = referencedTypes.get(dataNode.getPath());
} else if (leafListContainsEnumDefinition(dataNode)) {
- returnType = Types.listTypeFor(referencedTypes.get(
- dataNode.getPath()));
+ returnType = Types.listTypeFor(referencedTypes
+ .get(dataNode.getPath()));
} else {
returnType = resolveTypeFromDataSchemaNode(dataNode);
}
return false;
}
- private boolean leafListContainsEnumDefinition(
- final DataSchemaNode dataNode) {
+ private boolean leafListContainsEnumDefinition(final DataSchemaNode dataNode) {
if (dataNode instanceof LeafListSchemaNode) {
final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
if (leafList.getType() instanceof EnumTypeDefinition) {
private Enumeration resolveEnumFromTypeDefinition(
final EnumTypeDefinition enumTypeDef, final String enumName) {
if (enumTypeDef == null) {
- throw new IllegalArgumentException("EnumTypeDefinition reference " +
- "cannot be NULL!");
+ throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
}
if (enumTypeDef.getValues() == null) {
- throw new IllegalArgumentException("EnumTypeDefinition MUST " +
- "contain at least ONE value definition!");
+ throw new IllegalArgumentException("EnumTypeDefinition MUST contain at least ONE value definition!");
}
if (enumTypeDef.getQName() == null) {
- throw new IllegalArgumentException("EnumTypeDefinition MUST " +
- "contain NON-NULL QName!");
+ throw new IllegalArgumentException("EnumTypeDefinition MUST contain NON-NULL QName!");
}
if (enumTypeDef.getQName().getLocalName() == null) {
- throw new IllegalArgumentException("Local Name in " +
- "EnumTypeDefinition QName cannot be NULL!");
+ throw new IllegalArgumentException("Local Name in EnumTypeDefinition QName cannot be NULL!");
}
final String enumerationName = parseToClassName(enumName);
- Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
+ Module module = findParentModuleForTypeDefinition(schemaContext,
+ enumTypeDef);
final String basePackageName = moduleNamespaceToPackageName(module);
final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
final EnumTypeDefinition enumTypeDef, final String enumName,
final GeneratedTypeBuilder typeBuilder) {
if (enumTypeDef == null) {
- throw new IllegalArgumentException("EnumTypeDefinition reference " +
- "cannot be NULL!");
+ throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
}
if (enumTypeDef.getValues() == null) {
- throw new IllegalArgumentException("EnumTypeDefinition MUST " +
- "contain at least ONE value definition!");
+ throw new IllegalArgumentException("EnumTypeDefinition MUST contain at least ONE value definition!");
}
if (enumTypeDef.getQName() == null) {
- throw new IllegalArgumentException("EnumTypeDefinition MUST " +
- "contain NON-NULL QName!");
+ throw new IllegalArgumentException("EnumTypeDefinition MUST contain NON-NULL QName!");
}
if (enumTypeDef.getQName().getLocalName() == null) {
- throw new IllegalArgumentException("Local Name in " +
- "EnumTypeDefinition QName cannot be NULL!");
+ throw new IllegalArgumentException("Local Name in EnumTypeDefinition QName cannot be NULL!");
}
if (typeBuilder == null) {
- throw new IllegalArgumentException("Generated Type Builder " +
- "reference cannot be NULL!");
+ throw new IllegalArgumentException("Generated Type Builder reference cannot be NULL!");
}
final String enumerationName = parseToClassName(enumName);
}
private void updateEnumPairsFromEnumTypeDef(
- final EnumTypeDefinition enumTypeDef,
- final EnumBuilder enumBuilder) {
+ final EnumTypeDefinition enumTypeDef, final EnumBuilder enumBuilder) {
if (enumBuilder != null) {
final List<EnumPair> enums = enumTypeDef.getValues();
if (enums != null) {
private void resolveTypeDefsFromContext() {
final Set<Module> modules = schemaContext.getModules();
if (modules == null) {
- throw new IllegalArgumentException("Sef of Modules cannot be " +
- "NULL!");
+ throw new IllegalArgumentException("Sef of Modules cannot be NULL!");
}
for (final Module module : modules) {
if (module == null) {
final List<ExtendedType> extUnions = UnionDependencySort
.sort(typeDefinitions);
for (final ExtendedType extUnionType : extUnions) {
- addUnionGeneratedTypeDefinition(basePackageName, extUnionType);
+ addUnionGeneratedTypeDefinition(basePackageName,
+ extUnionType);
}
}
}
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)
returnType = resolveEnumFromTypeDefinition(enumTypeDef,
typedefName);
+ } else if (baseTypeDefinition instanceof BitsTypeDefinition) {
+ final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) baseTypeDefinition;
+ returnType = bitsTypedefToTransferObject(bitsTypeDefinition,
+ basePackageName, typedefName);
+
} else {
final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
.javaTypeForSchemaDefinitionType(baseTypeDefinition);
javaType);
}
if (returnType != null) {
- final Map<String, Type> typeMap = genTypeDefsContextMap.get
- (moduleName);
+ final Map<String, Type> typeMap = genTypeDefsContextMap
+ .get(moduleName);
if (typeMap != null) {
typeMap.put(typedefName, returnType);
}
final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
.addProperty(propertyName);
- genPropBuilder.addReturnType(javaType);
+ genPropBuilder.setReturnType(javaType);
genTOBuilder.addEqualsIdentity(genPropBuilder);
genTOBuilder.addHashIdentity(genPropBuilder);
genTOBuilder.addToStringProperty(genPropBuilder);
private void addUnionGeneratedTypeDefinition(final String basePackageName,
final TypeDefinition<?> typedef) {
if (basePackageName == null) {
- throw new IllegalArgumentException("Base Package Name cannot be " +
- "NULL!");
+ throw new IllegalArgumentException("Base Package Name cannot be NULL!");
}
if (typedef == null) {
- throw new IllegalArgumentException("Type Definition cannot be " +
- "NULL!");
+ throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typedef.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have " +
- "non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
if ((baseTypeDefinition != null)
&& (baseTypeDefinition instanceof UnionTypeDefinition)) {
final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
- final List<TypeDefinition<?>> unionTypes = unionTypeDef
- .getTypes();
- final Module parentModule = findParentModuleForTypeDefinition(schemaContext,
- typedef);
+ final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
+ final Module parentModule = findParentModuleForTypeDefinition(
+ schemaContext, typedef);
Map<String, Type> genTOsMap = null;
if (parentModule != null && parentModule.getName() != null) {
basePackageName, typedef);
if ((unionTypes != null) && (unionGenTransObject != null)) {
for (final TypeDefinition<?> unionType : unionTypes) {
- final String typeName = unionType.getQName()
- .getLocalName();
+ final String typeName = unionType.getQName().getLocalName();
if (unionType instanceof ExtendedType) {
- final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext,
- unionType);
- if (unionTypeModule != null && unionTypeModule.getName() != 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);
+ final GeneratedTransferObject genTransferObject = (GeneratedTransferObject) innerGenTOs
+ .get(typeName);
if (genTransferObject != null) {
updateUnionTypeAsProperty(unionGenTransObject,
genTransferObject,
}
}
} else if (unionType instanceof EnumTypeDefinition) {
- final EnumBuilder
- enumBuilder = resolveInnerEnumFromTypeDefinition(
+ final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
(EnumTypeDefinition) unionType, typeName,
unionGenTransObject);
final Type enumRefType = new ReferencedTypeImpl(
final GeneratedTOBuilder unionGenTransObject, final Type type,
final String propertyName) {
if (unionGenTransObject != null && type != null) {
- final GeneratedPropertyBuilder propBuilder =
- unionGenTransObject.addProperty(parseToValidParamName(
- propertyName));
- propBuilder.addReturnType(type);
+ final GeneratedPropertyBuilder propBuilder = unionGenTransObject
+ .addProperty(parseToValidParamName(propertyName));
+ propBuilder.setReturnType(type);
propBuilder.setReadOnly(false);
if (!(type instanceof Enumeration)) {
}
return null;
}
+
+ private GeneratedTransferObject bitsTypedefToTransferObject(
+ final BitsTypeDefinition bitsTypeDefinition, final String basePackageName, final String typedefName) {
+
+ if (bitsTypeDefinition == null) {
+ throw new IllegalArgumentException("Bits TypeDefinition cannot be NULL!");
+ }
+ if (basePackageName == null) {
+ throw new IllegalArgumentException("Base Package Name cannot be NULL!");
+ }
+ if (typedefName == null) {
+ throw new IllegalArgumentException("Type Definition Local Name cannot be NULL!");
+ }
+
+ final String typeDefName = parseToClassName(typedefName);
+ final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName);
+
+ final List<Bit> bitList = bitsTypeDefinition.getBits();
+ GeneratedPropertyBuilder genPropertyBuilder;
+ for (final Bit bit : bitList) {
+ String name = bit.getName();
+ genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
+ genPropertyBuilder.setReadOnly(false);
+ genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+
+ genTOBuilder.addEqualsIdentity(genPropertyBuilder);
+ genTOBuilder.addHashIdentity(genPropertyBuilder);
+ genTOBuilder.addToStringProperty(genPropertyBuilder);
+ }
+ return genTOBuilder.toInstance();
+ }
}
Enumeration linkUpDownTrapEnable = null;
Enumeration operStatus = null;
- final List<Enumeration> enums = genInterface.getEnumDefintions();
+ final List<Enumeration> enums = genInterface.getEnumerations();
assertNotNull("Generated Type Interface cannot contain NULL reference" +
" to Enumeration types!", enums);
assertEquals("Generated Type Interface MUST contain 2 Enumeration " +
import org.junit.Test;
import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
--- /dev/null
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Parameter;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+public class GeneretedTypesBitsTest {
+
+ private SchemaContext resolveSchemaContextFromFiles(
+ final String... yangFiles) {
+ final YangModelParser parser = new YangParserImpl();
+
+ final List<File> inputFiles = new ArrayList<File>();
+ for (int i = 0; i < yangFiles.length; ++i) {
+ inputFiles.add(new File(yangFiles[i]));
+ }
+
+ final Set<Module> modules = parser.parseYangModels(inputFiles);
+ return parser.resolveSchemaContext(modules);
+ }
+
+ @Test
+ public void testGeneretedTypesBitsTest() {
+ final String yangTypesPath = getClass().getResource(
+ "/simple-bits-demo.yang").getPath();
+
+ final SchemaContext context = resolveSchemaContextFromFiles(yangTypesPath);
+ assertTrue(context != null);
+
+ final BindingGenerator bindingGen = new BindingGeneratorImpl();
+ final List<Type> genTypes = bindingGen.generateTypes(context);
+ assertTrue(genTypes != null);
+
+ List<MethodSignature> methodSignaturesList = null;
+
+ boolean leafParentFound = false;
+
+ boolean byteTypeFound = false;
+ int classPropertiesNumb = 0;
+ int toStringPropertiesNum = 0;
+ int equalPropertiesNum = 0;
+ int hashPropertiesNum = 0;
+
+ String nameReturnParamType = "";
+ String nameMethodeParamType = "";
+ boolean getByteLeafMethodFound = false;
+ boolean setByteLeafMethodFound = false;
+ int setByteLeafMethodParamNum = 0;
+
+ for (final Type type : genTypes) {
+ if (type instanceof GeneratedTransferObject) { // searching for
+ // ByteType
+ final GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+ if (genTO.getName().equals("ByteType")) {
+ byteTypeFound = true;
+ List<GeneratedProperty> genProperties = genTO
+ .getProperties();
+ classPropertiesNumb = genProperties.size();
+
+ genProperties = null;
+ genProperties = genTO.getToStringIdentifiers();
+ toStringPropertiesNum = genProperties.size();
+
+ genProperties = null;
+ genProperties = genTO.getEqualsIdentifiers();
+ equalPropertiesNum = genProperties.size();
+
+ genProperties = null;
+ genProperties = genTO.getHashCodeIdentifiers();
+ hashPropertiesNum = genProperties.size();
+
+ }
+ } else if (type instanceof GeneratedType) { // searching for
+ // interface
+ // LeafParameterContainer
+ final GeneratedType genType = (GeneratedType) type;
+ if (genType.getName().compareTo("LeafParentContainer") == 0) {
+ leafParentFound = true;
+ // check of methods
+ methodSignaturesList = genType.getMethodDefinitions();
+ if (methodSignaturesList != null) {
+ for (MethodSignature methodSignature : methodSignaturesList) { // loop
+ // through
+ // all
+ // methods
+ if (methodSignature.getName().compareTo(
+ "getByteLeaf") == 0) {
+ getByteLeafMethodFound = true;
+
+ nameReturnParamType = methodSignature
+ .getReturnType().getName();
+ } else if (methodSignature.getName().compareTo(
+ "setByteLeaf") == 0) {
+ setByteLeafMethodFound = true;
+
+ List<Parameter> parameters = methodSignature
+ .getParameters();
+ setByteLeafMethodParamNum = parameters.size();
+ for (Parameter parameter : parameters) {
+ nameMethodeParamType = parameter.getType()
+ .getName();
+ }
+
+ }
+
+ }
+ }
+ }
+ }
+
+ }
+
+ assertTrue("type >ByteType< wasn't in YANG file", byteTypeFound == true);
+
+ assertTrue("Incorrect number of bit properties in class",
+ classPropertiesNumb == 8);
+
+ assertTrue("Incorrect number of properties in toString method",
+ toStringPropertiesNum == 8);
+ assertTrue("Incorrect number of properties in equals method",
+ equalPropertiesNum == 8);
+ assertTrue("Incorrect number of properties in hash method",
+ hashPropertiesNum == 8);
+ assertTrue("LeafParameterContainer container wasn't found",
+ leafParentFound == true);
+
+ assertTrue("No methods were generated", methodSignaturesList != null);
+
+ assertTrue("Method getByteLeaf wasn't generated.",
+ getByteLeafMethodFound == true);
+ assertTrue("Wrong returning parameter type of method getByteLeaf",
+ nameReturnParamType.compareTo("ByteType") == 0);
+
+ assertTrue("Method setByteLeaf wasn't generated.",
+ setByteLeafMethodFound == true);
+ assertTrue("Incorrect number of input parameters for setByteLeaf",
+ setByteLeafMethodParamNum == 1);
+ assertTrue("Wrong input parameter type",
+ nameMethodeParamType.compareTo("ByteType") == 0);
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+module simple-bits-demo {
+
+ namespace "urn:simple:bits:demo";
+ prefix "sbd";
+
+ organization "OPEN DAYLIGHT";
+ contact "http://www.opendaylight.org/";
+
+ revision 2013-06-11 {
+
+ }
+
+ typedef byte-type {
+ type bits {
+ bit first-bit {
+ position 10;
+ }
+ bit second-bit {
+ position 20;
+ }
+ bit third-bit {
+ position 30;
+ }
+ bit forth-bit {
+ position 40;
+ }
+ bit fifth-bit {
+ position 50;
+ }
+ bit sixth-bit {
+ position 60;
+ }
+ bit seventh-bit {
+ position 70;
+ }
+ bit eight-bit {
+ position 80;
+ }
+
+ }
+
+ typedef jo {
+ type uint32;
+ }
+
+
+ container leaf-parent-container {
+ leaf byte-leaf {
+ type byte-type;
+ }
+
+ }
+
+}
\ No newline at end of file
return name;\r
}\r
\r
+ @Override\r
+ public String getFullyQualifiedName() {\r
+ if (packageName.isEmpty()) {\r
+ return name;\r
+ } else {\r
+ return packageName + "." + name;\r
+ }\r
+ }\r
+\r
protected AbstractBaseType(String pkName, String name) {\r
this.packageName = pkName;\r
this.name = name;\r
}\r
return "Type (" + packageName + "." + name + ")";\r
}\r
-\r
}\r
*/
package org.opendaylight.controller.binding.generator.util;
-import org.opendaylight.controller.sal.binding.model.api.Type;
+public final class ReferencedTypeImpl extends AbstractBaseType {
-
-public final class ReferencedTypeImpl implements Type {
-
- private final String packageName;
- private final String name;
-
public ReferencedTypeImpl(String packageName, String name) {
- super();
- this.packageName = packageName;
- this.name = name;
- }
-
- /* (non-Javadoc)
- * @see org.opendaylight.controller.sal.binding.model.api.Type#getPackageName()
- */
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- /* (non-Javadoc)
- * @see org.opendaylight.controller.sal.binding.model.api.Type#getName()
- */
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result
- + ((packageName == null) ? 0 : packageName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- ReferencedTypeImpl other = (ReferencedTypeImpl) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (packageName == null) {
- if (other.packageName != null) {
- return false;
- }
- } else if (!packageName.equals(other.packageName)) {
- return false;
- }
- return true;
+ super(packageName, name);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ReferencedTypeImpl [packageName=");
- builder.append(packageName);
+ builder.append(getPackageName());
builder.append(", name=");
- builder.append(name);
+ builder.append(getName());
builder.append("]");
return builder.toString();
}
--- /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.binding.generator.util.generated.type.builder;
+
+
+import org.opendaylight.controller.binding.generator.util.AbstractBaseType;
+import org.opendaylight.controller.sal.binding.model.api.*;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+abstract class AbstractGeneratedType extends AbstractBaseType implements GeneratedType {
+
+ private final Type parent;
+ private final String comment;
+ private final List<AnnotationType> annotations;
+ private final List<Type> implementsTypes;
+ private final List<Enumeration> enumerations;
+ private final List<Constant> constants;
+ private final List<MethodSignature> methodSignatures;
+ private final List<GeneratedType> enclosedTypes;
+ private final boolean isAbstract;
+
+ public AbstractGeneratedType(final Type parent, final String packageName,
+ final String name, final String comment,
+ final List<AnnotationTypeBuilder> annotationBuilders,
+ final boolean isAbstract,
+ final List<Type> implementsTypes,
+ final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+ final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+ final List<EnumBuilder> enumBuilders,
+ final List<Constant> constants,
+ final List<MethodSignatureBuilder> methodBuilders) {
+ super(packageName, name);
+ this.parent = parent;
+ this.comment = comment;
+ this.annotations = toUnmodifiableAnnotations(annotationBuilders);
+ this.implementsTypes = Collections.unmodifiableList(implementsTypes);
+ this.constants = toUnmodifiableConstants(constants);
+ this.enumerations = toUnmodifiableEnumerations(enumBuilders);
+ this.methodSignatures = toUnmodifiableMethods(methodBuilders);
+ this.enclosedTypes = toUnmodifiableEnclosedTypes(enclosedGenTypeBuilders, enclosedGenTOBuilders);
+ this.isAbstract = isAbstract;
+ }
+
+ private List<GeneratedType> toUnmodifiableEnclosedTypes(final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+ final List<GeneratedTOBuilder> enclosedGenTOBuilders) {
+ final List<GeneratedType> enclosedTypes = new ArrayList<>();
+ for (final GeneratedTypeBuilder builder : enclosedGenTypeBuilders) {
+ if (builder != null) {
+ enclosedTypes.add(builder.toInstance());
+ }
+ }
+
+ for (final GeneratedTOBuilder builder : enclosedGenTOBuilders) {
+ if (builder != null) {
+ enclosedTypes.add(builder.toInstance());
+ }
+ }
+ return enclosedTypes;
+ }
+
+ protected List<AnnotationType> toUnmodifiableAnnotations(
+ final List<AnnotationTypeBuilder> annotationBuilders) {
+ final List<AnnotationType> annotations = new ArrayList<>();
+ for (final AnnotationTypeBuilder builder : annotationBuilders) {
+ annotations.add(builder.toInstance());
+ }
+ return Collections.unmodifiableList(annotations);
+ }
+
+ protected List<MethodSignature> toUnmodifiableMethods(
+ List<MethodSignatureBuilder> methodBuilders) {
+ final List<MethodSignature> methods = new ArrayList<>();
+ for (final MethodSignatureBuilder methodBuilder : methodBuilders) {
+ methods.add(methodBuilder.toInstance(this));
+ }
+ return Collections.unmodifiableList(methods);
+ }
+
+ protected List<Enumeration> toUnmodifiableEnumerations(
+ List<EnumBuilder> enumBuilders) {
+ final List<Enumeration> enums = new ArrayList<>();
+ for (final EnumBuilder enumBuilder : enumBuilders) {
+ enums.add(enumBuilder.toInstance(this));
+ }
+ return Collections.unmodifiableList(enums);
+ }
+
+ protected List<Constant> toUnmodifiableConstants(
+ List<Constant> constants) {
+ for (final Constant constant : constants) {
+ constants.add(new ConstantImpl(this, constant.getType(),
+ constant.getName(), constant.getValue()));
+ }
+ return Collections.unmodifiableList(constants);
+ }
+
+ @Override
+ public Type getParentType() {
+ return parent;
+ }
+
+ @Override
+ public String getComment() {
+ return comment;
+ }
+
+ @Override
+ public List<AnnotationType> getAnnotations() {
+ return annotations;
+ }
+
+ @Override
+ public boolean isAbstract() {
+ return isAbstract;
+ }
+
+ @Override
+ public List<Type> getImplements() {
+ return implementsTypes;
+ }
+
+ @Override
+ public List<GeneratedType> getEnclosedTypes() {
+ return enclosedTypes;
+ }
+
+ @Override
+ public List<Enumeration> getEnumerations() {
+ return enumerations;
+ }
+
+ @Override
+ public List<Constant> getConstantDefinitions() {
+ return constants;
+ }
+
+ @Override
+ public List<MethodSignature> getMethodDefinitions() {
+ return methodSignatures;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedType [packageName=");
+ builder.append(getPackageName());
+ builder.append(", name=");
+ builder.append(getName());
+ if (parent != null) {
+ builder.append(", parent=");
+ builder.append(parent.getFullyQualifiedName());
+ } else {
+ builder.append(", parent=null");
+ }
+ builder.append(", comment=");
+ builder.append(comment);
+ builder.append(", annotations=");
+ builder.append(annotations);
+ builder.append(", enclosedTypes=");
+ builder.append(enclosedTypes);
+ builder.append(", enumerations=");
+ builder.append(enumerations);
+ builder.append(", constants=");
+ builder.append(constants);
+ builder.append(", methodSignatures=");
+ builder.append(methodSignatures);
+ builder.append("]");
+ return builder.toString();
+ }
+}
--- /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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.Constant;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+abstract class AbstractGeneratedTypeBuilder implements GeneratedTypeBuilder {
+
+ private final String packageName;
+ private String comment = "";
+ private final String name;
+
+ private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<>();
+ private final List<Type> implementsTypes = new ArrayList<>();
+ private final List<EnumBuilder> enumDefinitions = new ArrayList<>();
+ private final List<Constant> constants = new ArrayList<>();
+ private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<>();
+ private final List<GeneratedTypeBuilder> enclosedTypes = new ArrayList<>();
+ private final List<GeneratedTOBuilder> enclosingTransferObjects = new ArrayList<>();
+ private boolean isAbstract;
+
+ public AbstractGeneratedTypeBuilder(final String packageName, final String name) {
+ if (packageName == null) {
+ throw new IllegalArgumentException("Package Name for Generated Type cannot be null!");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name of Generated Type cannot be null!");
+ }
+ this.packageName = packageName;
+ this.name = name;
+ }
+
+ @Override
+ public String getPackageName() {
+ return packageName;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
+
+ protected String getComment() {
+ return comment;
+ }
+
+ protected List<AnnotationTypeBuilder> getAnnotations() {
+ return annotationBuilders;
+ }
+
+ protected boolean isAbstract() {
+ return isAbstract;
+ }
+
+ protected List<Type> getImplementsTypes() {
+ return implementsTypes;
+ }
+
+ protected List<EnumBuilder> getEnumerations() {
+ return enumDefinitions;
+ }
+
+ protected List<Constant> getConstants() {
+ return constants;
+ }
+
+ protected List<MethodSignatureBuilder> getMethodDefinitions() {
+ return methodDefinitions;
+ }
+
+ protected List<GeneratedTypeBuilder> getEnclosedTypes() {
+ return enclosedTypes;
+ }
+
+ protected List<GeneratedTOBuilder> getEnclosedTransferObjects() {
+ return enclosingTransferObjects;
+ }
+
+ @Override
+ public GeneratedTypeBuilder addEnclosingType(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Name for Enclosing Generated Type cannot be null!");
+ }
+ GeneratedTypeBuilder builder = new GeneratedTOBuilderImpl(getFullyQualifiedName(), name);
+ enclosedTypes.add(builder);
+ return builder;
+ }
+
+ @Override
+ public GeneratedTOBuilder addEnclosingTransferObject(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Name for Enclosing Generated Transfer Object cannot be null!");
+ }
+ GeneratedTOBuilder builder = new GeneratedTOBuilderImpl(getFullyQualifiedName(), name);
+ enclosingTransferObjects.add(builder);
+ return builder;
+ }
+
+ @Override
+ public void addComment(String comment) {
+ this.comment = comment;
+ }
+
+ @Override
+ public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
+ if (packageName == null) {
+ throw new IllegalArgumentException("Package Name for Annotation Type cannot be null!");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name of Annotation Type cannot be null!");
+ }
+
+ final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, name);
+ annotationBuilders.add(builder);
+ return builder;
+ }
+
+ @Override
+ public void setAbstract(boolean isAbstract) {
+ this.isAbstract = isAbstract;
+ }
+
+ @Override
+ public boolean addImplementsType(Type genType) {
+ if (genType == null) {
+ throw new IllegalArgumentException("Type cannot be null");
+ }
+ return implementsTypes.add(genType);
+ }
+
+ @Override
+ public Constant addConstant(Type type, String name, Object value) {
+ if (type == null) {
+ throw new IllegalArgumentException("Returning Type for Constant cannot be null!");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name of constant cannot be null!");
+ }
+
+ final Constant constant = new ConstantImpl(this, type, name, value);
+ constants.add(constant);
+ return constant;
+ }
+
+ @Override
+ public EnumBuilder addEnumeration(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Name of enumeration cannot be null!");
+ }
+ final EnumBuilder builder = new EnumerationBuilderImpl(
+ getFullyQualifiedName(), name);
+ enumDefinitions.add(builder);
+ return builder;
+ }
+
+ @Override
+ public MethodSignatureBuilder addMethod(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Name of method cannot be null!");
+ }
+ final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(name);
+ builder.setAccessModifier(AccessModifier.PUBLIC);
+ builder.setAbstract(true);
+ methodDefinitions.add(builder);
+ return builder;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+ result = prime * result
+ + ((getPackageName() == null) ? 0 : getPackageName().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ AbstractGeneratedTypeBuilder other = (AbstractGeneratedTypeBuilder) obj;
+ if (getName() == null) {
+ if (other.getName() != null) {
+ return false;
+ }
+ } else if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (getPackageName() == null) {
+ if (other.getPackageName() != null) {
+ return false;
+ }
+ } else if (!getPackageName().equals(other.getPackageName())) {
+ return false;
+ }
+ return true;
+ }
+}
--- /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.binding.generator.util.generated.type.builder;
+
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.TypeMember;
+
+import java.util.Collections;
+import java.util.List;
+
+abstract class AbstractTypeMember implements TypeMember {
+
+ private final String name;
+ private final String comment;
+ private final Type definingType;
+ private final Type returnType;
+ private final List<AnnotationType> annotations;
+ private final boolean isFinal;
+ private final AccessModifier accessModifier;
+
+ public AbstractTypeMember(final Type definingType, final String name, final List<AnnotationType> annotations,
+ final String comment, final AccessModifier accessModifier, final Type returnType,
+ boolean isFinal) {
+ super();
+ this.definingType = definingType;
+ this.name = name;
+ this.annotations = Collections.unmodifiableList(annotations);
+ this.comment = comment;
+ this.accessModifier = accessModifier;
+ this.returnType = returnType;
+ this.isFinal = isFinal;
+ }
+
+ @Override
+ public List<AnnotationType> getAnnotations() {
+ return annotations;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getComment() {
+ return comment;
+ }
+
+ @Override
+ public Type getDefiningType() {
+ return definingType;
+ }
+
+ @Override
+ public AccessModifier getAccessModifier() {
+ return accessModifier;
+ }
+
+ @Override
+ public Type getReturnType() {
+ return returnType;
+ }
+
+ @Override
+ public boolean isFinal() {
+ return isFinal;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+ result = prime * result
+ + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ MethodSignatureImpl other = (MethodSignatureImpl) obj;
+ if (getName() == null) {
+ if (other.getName() != null) {
+ return false;
+ }
+ } else if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (getReturnType() == null) {
+ if (other.getReturnType() != null) {
+ return false;
+ }
+ } else if (!getReturnType().equals(other.getReturnType())) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("MethodSignatureImpl [name=");
+ builder.append(getName());
+ builder.append(", comment=");
+ builder.append(getComment());
+ if (getDefiningType() != null) {
+ builder.append(", definingType=");
+ builder.append(getDefiningType().getPackageName());
+ builder.append(".");
+ builder.append(getDefiningType().getName());
+ } else {
+ builder.append(", definingType= null");
+ }
+ builder.append(", returnType=");
+ builder.append(getReturnType());
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append("]");
+ return builder.toString();
+ }
+}
--- /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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.TypeMemberBuilder;
+
+import java.util.ArrayList;
+import java.util.List;
+
+abstract class AbstractTypeMemberBuilder implements TypeMemberBuilder {
+ private final String name;
+ private Type returnType;
+ private final List<AnnotationTypeBuilder> annotationBuilders;
+ private String comment = "";
+ private boolean isFinal;
+ private AccessModifier accessModifier;
+
+ public AbstractTypeMemberBuilder(final String name) {
+ this.name = name;
+ this.annotationBuilders = new ArrayList<>();
+ }
+
+ @Override
+ public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
+ if (packageName == null) {
+ throw new IllegalArgumentException("Annotation Type cannot have package name null!");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Annotation Type cannot have name as null!");
+ }
+ final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
+ packageName, name);
+ annotationBuilders.add(builder);
+ return builder;
+ }
+
+ protected Type getReturnType() {
+ return returnType;
+ }
+
+ protected List<AnnotationTypeBuilder> getAnnotationBuilders() {
+ return annotationBuilders;
+ }
+
+ protected String getComment() {
+ return comment;
+ }
+
+ protected boolean isFinal() {
+ return isFinal;
+ }
+
+ protected AccessModifier getAccessModifier() {
+ return accessModifier;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void setReturnType(Type returnType) {
+ if (returnType == null) {
+ throw new IllegalArgumentException("Return Type of member cannot be null!");
+ }
+ this.returnType = returnType;
+ }
+
+ @Override
+ public void setAccessModifier(AccessModifier modifier) {
+ if (modifier == null) {
+ throw new IllegalArgumentException("Access Modifier for member type cannot be null!");
+ }
+ this.accessModifier = modifier;
+ }
+
+ @Override
+ public void setComment(String comment) {
+ if (comment == null) {
+ throw new IllegalArgumentException("Comment string cannot be null!");
+ }
+ this.comment = comment;
+ }
+
+ @Override
+ public void setFinal(boolean isFinal) {
+ this.isFinal = isFinal;
+ }
+
+ protected List<AnnotationType> toAnnotationTypes() {
+ final List<AnnotationType> annotations = new ArrayList<>();
+ for (final AnnotationTypeBuilder annotBuilder : getAnnotationBuilders()) {
+ if (annotBuilder != null) {
+ annotations.add(annotBuilder.toInstance());
+ }
+ }
+ return annotations;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+ result = prime * result
+ + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ MethodSignatureBuilderImpl other = (MethodSignatureBuilderImpl) obj;
+ if (getName() == null) {
+ if (other.getName() != null) {
+ return false;
+ }
+ } else if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (getReturnType() == null) {
+ if (other.getReturnType() != null) {
+ return false;
+ }
+ } else if (!getReturnType().equals(other.getReturnType())) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedPropertyImpl [name=");
+ builder.append(getName());
+ builder.append(", annotations=");
+ builder.append(getAnnotationBuilders());
+ builder.append(", comment=");
+ builder.append(getComment());
+ builder.append(", returnType=");
+ builder.append(getReturnType());
+ builder.append(", isFinal=");
+ builder.append(isFinal());
+ builder.append(", modifier=");
+ builder.append(getAccessModifier());
+ builder.append("]");
+ return builder.toString();
+ }
+}
+/*
+ * 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.binding.generator.util.generated.type.builder;
import java.util.ArrayList;
super();
this.packageName = packageName;
this.name = name;
-
- annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
- parameters = new ArrayList<AnnotationType.Parameter>();
+ annotationBuilders = new ArrayList<>();
+ parameters = new ArrayList<>();
}
@Override
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
if (packageName != null && name != null) {
this.packageName = packageName;
this.name = name;
- this.annotations = new ArrayList<AnnotationType>();
+ this.annotations = new ArrayList<>();
for (final AnnotationTypeBuilder builder : annotationBuilders) {
annotations.add(builder.toInstance());
}
this.annotations = Collections.unmodifiableList(annotations);
this.parameters = Collections.unmodifiableList(parameters);
- paramNames = new ArrayList<String>();
+ paramNames = new ArrayList<>();
for (final AnnotationType.Parameter parameter : parameters) {
paramNames.add(parameter.getName());
}
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public List<AnnotationType> getAnnotations() {
return annotations;
+++ /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.binding.generator.util.generated.type.builder;
-
-import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-
-final class ConstantBuilderImpl implements ConstantBuilder {
-
- private final Type type;
- private final String name;
- private Object value;
-
- public ConstantBuilderImpl(Type type, String name, Object value) {
- super();
- this.type = type;
- this.name = name;
- this.value = value;
- }
-
- public ConstantBuilderImpl(Type type, String name) {
- super();
- this.type = type;
- this.name = name;
- }
-
- @Override
- public void assignValue(Object value) {
- this.value = value;
- }
-
- @Override
- public Constant toInstance(final Type definingType) {
- return new ConstantImpl(definingType, type, name, value);
- }
-
- private static final class ConstantImpl implements Constant {
-
- final Type definingType;
- private final Type type;
- private final String name;
- private final Object value;
-
- public ConstantImpl(final Type definingType, final Type type,
- final String name, final Object value) {
- super();
- this.definingType = definingType;
- this.type = type;
- this.name = name;
- this.value = value;
- }
-
- @Override
- public Type getDefiningType() {
- return definingType;
- }
-
- @Override
- public Type getType() {
- return type;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Object getValue() {
- return value;
- }
-
- @Override
- public String toFormattedString() {
- StringBuilder builder = new StringBuilder();
- builder.append(type);
- builder.append(" ");
- builder.append(name);
- builder.append(" ");
- builder.append(value);
- return builder.toString();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- return result;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- ConstantImpl other = (ConstantImpl) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (type == null) {
- if (other.type != null) {
- return false;
- }
- } else if (!type.equals(other.type)) {
- return false;
- }
- if (value == null) {
- if (other.value != null) {
- return false;
- }
- } else if (!value.equals(other.value)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("Constant [type=");
- builder.append(type);
- builder.append(", name=");
- builder.append(name);
- builder.append(", value=");
- builder.append(value);
- if (definingType != null) {
- builder.append(", definingType=");
- builder.append(definingType.getPackageName());
- builder.append(".");
- builder.append(definingType.getName());
- } else {
- builder.append(", definingType= null");
- }
- builder.append("]");
- return builder.toString();
- }
- }
-}
--- /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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.Constant;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+final class ConstantImpl implements Constant {
+
+ final Type definingType;
+ private final Type type;
+ private final String name;
+ private final Object value;
+
+ public ConstantImpl(final Type definingType, final Type type,
+ final String name, final Object value) {
+ super();
+ this.definingType = definingType;
+ this.type = type;
+ this.name = name;
+ this.value = value;
+ }
+
+ @Override
+ public Type getDefiningType() {
+ return definingType;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public Object getValue() {
+ return value;
+ }
+
+ @Override
+ public String toFormattedString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append(type);
+ builder.append(" ");
+ builder.append(name);
+ builder.append(" ");
+ builder.append(value);
+ return builder.toString();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ ConstantImpl other = (ConstantImpl) obj;
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ if (type == null) {
+ if (other.type != null) {
+ return false;
+ }
+ } else if (!type.equals(other.type)) {
+ return false;
+ }
+ if (value == null) {
+ if (other.value != null) {
+ return false;
+ }
+ } else if (!value.equals(other.value)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("Constant [type=");
+ builder.append(type);
+ builder.append(", name=");
+ builder.append(name);
+ builder.append(", value=");
+ builder.append(value);
+ if (definingType != null) {
+ builder.append(", definingType=");
+ builder.append(definingType.getPackageName());
+ builder.append(".");
+ builder.append(definingType.getName());
+ } else {
+ builder.append(", definingType= null");
+ }
+ builder.append("]");
+ return builder.toString();
+ }
+}
super();
this.packageName = packageName;
this.name = name;
- values = new ArrayList<Enumeration.Pair>();
+ values = new ArrayList<>();
}
@Override
public String getName() {
return name;
}
-
+
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
if (packageName != null && name != null) {
private final String packageName;
private final String name;
private final List<Pair> values;
- private List<AnnotationType> annotations = new ArrayList<AnnotationType>();
+ private List<AnnotationType> annotations = new ArrayList<>();
public EnumerationImpl(final Type definingType,
final List<AnnotationTypeBuilder> annotationBuilders,
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public List<Pair> getValues() {
return values;
--- /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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
+
+import java.util.List;
+
+final class GeneratedPropertyBuilderImpl extends AbstractTypeMemberBuilder implements GeneratedPropertyBuilder {
+
+ private boolean isReadOnly;
+
+ public GeneratedPropertyBuilderImpl(String name) {
+ super(name);
+ }
+
+ @Override
+ public void setReadOnly(boolean isReadOnly) {
+ this.isReadOnly = isReadOnly;
+ }
+
+ @Override
+ public GeneratedProperty toInstance(Type definingType) {
+ final List<AnnotationType> annotations = toAnnotationTypes();
+ return new GeneratedPropertyImpl(definingType, getName(), annotations, getComment(), getAccessModifier(),
+ getReturnType(), isFinal(), isReadOnly);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedPropertyImpl [name=");
+ builder.append(getName());
+ builder.append(", annotations=");
+ builder.append(getAnnotationBuilders());
+ builder.append(", comment=");
+ builder.append(getComment());
+ builder.append(", returnType=");
+ builder.append(getReturnType());
+ builder.append(", isFinal=");
+ builder.append(isFinal());
+ builder.append(", isReadOnly=");
+ builder.append(isReadOnly);
+ builder.append(", modifier=");
+ builder.append(getAccessModifier());
+ builder.append("]");
+ return builder.toString();
+ }
+}
\ 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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+import java.util.List;
+
+final class GeneratedPropertyImpl extends AbstractTypeMember implements GeneratedProperty {
+
+ private boolean isReadOnly;
+
+ public GeneratedPropertyImpl(Type definingType, String name, List<AnnotationType> annotations, String comment,
+ AccessModifier accessModifier, Type returnType, boolean isFinal, boolean isReadOnly) {
+ super(definingType, name, annotations, comment, accessModifier, returnType, isFinal);
+ this.isReadOnly = isReadOnly;
+ }
+
+ @Override
+ public boolean isReadOnly() {
+ return isReadOnly;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedPropertyImpl [name=");
+ builder.append(getName());
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append(", comment=");
+ builder.append(getComment());
+ if (getDefiningType() != null) {
+ builder.append(", parent=");
+ builder.append(getDefiningType().getPackageName());
+ builder.append(".");
+ builder.append(getDefiningType().getName());
+ } else {
+ builder.append(", parent=null");
+ }
+ builder.append(", returnType=");
+ builder.append(getReturnType());
+ builder.append(", isFinal=");
+ builder.append(isFinal());
+ builder.append(", isReadOnly=");
+ builder.append(isReadOnly);
+ builder.append(", modifier=");
+ builder.append(getAccessModifier());
+ builder.append("]");
+ return builder.toString();
+ }
+}
*/
package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+import org.opendaylight.controller.sal.binding.model.api.*;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
-import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
-import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferIdentityObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
-import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
-
-public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
- private String packageName;
- private final String name;
- private String comment = "";
+public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder implements GeneratedTOBuilder {
private GeneratedTransferObject extendsType;
- private final List<Type> implementsTypes = new ArrayList<Type>();
- private final List<EnumBuilder> enumerations = new ArrayList<EnumBuilder>();
- private final List<GeneratedPropertyBuilder> properties = new ArrayList<GeneratedPropertyBuilder>();
- private final List<GeneratedPropertyBuilder> equalsProperties = new ArrayList<GeneratedPropertyBuilder>();
- private final List<GeneratedPropertyBuilder> hashProperties = new ArrayList<GeneratedPropertyBuilder>();
- private final List<GeneratedPropertyBuilder> toStringProperties = new ArrayList<GeneratedPropertyBuilder>();
-
- private final List<ConstantBuilder> constantDefintions = new ArrayList<ConstantBuilder>();
- private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<MethodSignatureBuilder>();
- private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
+ private final List<GeneratedPropertyBuilder> properties = new ArrayList<>();
+ private final List<GeneratedPropertyBuilder> equalsProperties = new ArrayList<>();
+ private final List<GeneratedPropertyBuilder> hashProperties = new ArrayList<>();
+ private final List<GeneratedPropertyBuilder> toStringProperties = new ArrayList<>();
public GeneratedTOBuilderImpl(String packageName, String name) {
- super();
- this.packageName = packageName;
- this.name = name;
- }
-
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Type getParentType() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void addComment(final String comment) {
- this.comment = comment;
- }
-
- @Override
- public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
- if (packageName != null && name != null) {
- final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
- packageName, name);
- if (annotationBuilders.add(builder)) {
- return builder;
- }
- }
- return null;
- }
-
- @Override
- public boolean addImplementsType(final Type genType) {
- if (genType != null) {
- return implementsTypes.add(genType);
- }
- return false;
+ super(packageName, name);
+ setAbstract(false);
}
@Override
- public boolean addExtendsType(final GeneratedTransferObject genTransObj) {
- if (genTransObj != null) {
- extendsType = genTransObj;
- return true;
+ public void setExtendsType(final GeneratedTransferObject genTransObj) {
+ if (genTransObj == null) {
+ throw new IllegalArgumentException("Generated Transfer Object cannot be null!");
}
- return false;
- }
-
- @Override
- public EnumBuilder addEnumeration(String name) {
- final String innerPackageName = packageName + "." + this.name;
- final EnumBuilder builder = new EnumerationBuilderImpl(innerPackageName,
- name);
- enumerations.add(builder);
- return builder;
+ extendsType = genTransObj;
}
@Override
- public ConstantBuilder addConstant(Type type, String name, Object value) {
- final ConstantBuilder builder = new ConstantBuilderImpl(type, name,
- value);
- constantDefintions.add(builder);
+ public GeneratedPropertyBuilder addProperty(String name) {
+ final GeneratedPropertyBuilder builder = new GeneratedPropertyBuilderImpl(name);
+ builder.setAccessModifier(AccessModifier.PUBLIC);
+ properties.add(builder);
return builder;
}
+ /**
+ * Add new Method Signature definition for Generated Type Builder and
+ * returns Method Signature Builder for specifying all Method parameters.
+ * <br>
+ * Name of Method cannot be <code>null</code>,
+ * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+ * <br>
+ * By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
+ * {@link MethodSignatureBuilder#setAbstract(false)}, {@link MethodSignatureBuilder#setFinal(false)} and
+ * {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
+ *
+ * @param name Name of Method
+ * @return <code>new</code> instance of Method Signature Builder.
+ */
@Override
public MethodSignatureBuilder addMethod(String name) {
- final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(
- this, name);
- methodDefinitions.add(builder);
- return builder;
- }
-
- @Override
- public GeneratedPropertyBuilder addProperty(String name) {
- final GeneratedPropertyBuilder builder = new GeneratedPropertyBuilderImpl(
- name);
- properties.add(builder);
+ final MethodSignatureBuilder builder = super.addMethod(name);
+ builder.setAbstract(false);
return builder;
}
@Override
public GeneratedTransferObject toInstance() {
- return new GeneratedTransferObjectImpl(packageName, name, comment,
- annotationBuilders, extendsType, implementsTypes,
- constantDefintions, enumerations, methodDefinitions,
- properties, equalsProperties, hashProperties,
- toStringProperties);
- }
-
- @Override
- public GeneratedTransferObject toIdentityInstance() {
- return new GeneratedTransferIdentityObjectImpl(packageName, name, comment,
- annotationBuilders, extendsType, implementsTypes,
- constantDefintions, enumerations, methodDefinitions,
- properties, equalsProperties, hashProperties,
- toStringProperties);
- }
-
- private static final class GeneratedPropertyBuilderImpl implements
- GeneratedPropertyBuilder {
-
- private final String name;
- private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
- private Type returnType;
- private final List<MethodSignature.Parameter> parameters;
- private String comment = "";
- private AccessModifier accessModifier;
- private boolean isFinal;
- private boolean isReadOnly;
-
- public GeneratedPropertyBuilderImpl(final String name) {
- super();
- this.name = name;
- parameters = new ArrayList<MethodSignature.Parameter>();
- isFinal = true;
- this.isReadOnly = true;
- accessModifier = AccessModifier.PUBLIC;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public AnnotationTypeBuilder addAnnotation(String packageName,
- String name) {
- if (packageName != null && name != null) {
- final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
- packageName, name);
- if (annotationBuilders.add(builder)) {
- return builder;
- }
- }
- return null;
- }
-
- @Override
- public boolean addReturnType(Type returnType) {
- if (returnType != null) {
- this.returnType = returnType;
- this.parameters.add(new MethodParameterImpl(name, returnType));
- return true;
- }
- return false;
- }
-
- @Override
- public void accessorModifier(final AccessModifier modifier) {
- accessModifier = modifier;
- }
-
- @Override
- public void addComment(String comment) {
- if (comment != null) {
- this.comment = comment;
- }
- }
-
- @Override
- public void setFinal(boolean isFinal) {
- this.isFinal = isFinal;
- }
-
- @Override
- public void setReadOnly(boolean isReadOnly) {
- this.isReadOnly = isReadOnly;
- }
-
- @Override
- public GeneratedProperty toInstance(final Type definingType) {
- return new GeneratedPropertyImpl(name, comment, annotationBuilders,
- definingType, returnType, isFinal, isReadOnly, parameters,
- accessModifier);
- }
- }
-
- private static final class GeneratedPropertyImpl implements
- GeneratedProperty {
-
- private final String name;
- private List<AnnotationType> annotations;
- private final String comment;
- private final Type parent;
- private final Type returnType;
- private final boolean isFinal;
- private final boolean isReadOnly;
- private final List<MethodSignature.Parameter> parameters;
- private final AccessModifier modifier;
-
- public GeneratedPropertyImpl(final String name, final String comment,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final Type parent, final Type returnType,
- final boolean isFinal, final boolean isReadOnly,
- final List<Parameter> parameters, final AccessModifier modifier) {
- super();
- this.name = name;
- this.annotations = new ArrayList<AnnotationType>();
- for (final AnnotationTypeBuilder builder : annotationBuilders) {
- this.annotations.add(builder.toInstance());
- }
- this.annotations = Collections.unmodifiableList(this.annotations);
- this.comment = comment;
- this.parent = parent;
- this.returnType = returnType;
- this.isFinal = isFinal;
- this.isReadOnly = isReadOnly;
- this.parameters = Collections.unmodifiableList(parameters);
- this.modifier = modifier;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public String getComment() {
- return comment;
- }
-
- @Override
- public Type getDefiningType() {
- return parent;
- }
-
- @Override
- public List<AnnotationType> getAnnotations() {
- return annotations;
- }
-
- @Override
- public Type getReturnType() {
- return returnType;
- }
-
- @Override
- public List<Parameter> getParameters() {
- return parameters;
- }
-
- @Override
- public AccessModifier getAccessModifier() {
- return modifier;
- }
-
- @Override
- public boolean isReadOnly() {
- return isReadOnly;
- }
-
- @Override
- public boolean isFinal() {
- return isFinal;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result
- + ((parameters == null) ? 0 : parameters.hashCode());
- result = prime * result
- + ((returnType == null) ? 0 : returnType.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- GeneratedPropertyImpl other = (GeneratedPropertyImpl) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (parameters == null) {
- if (other.parameters != null) {
- return false;
- }
- } else if (!parameters.equals(other.parameters)) {
- return false;
- }
- if (returnType == null) {
- if (other.returnType != null) {
- return false;
- }
- } else if (!returnType.getPackageName().equals(
- other.returnType.getPackageName())) {
- return false;
- } else if (!returnType.getName().equals(other.returnType.getName())) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("GeneratedPropertyImpl [name=");
- builder.append(name);
- builder.append(", annotations=");
- builder.append(annotations);
- builder.append(", comment=");
- builder.append(comment);
- if (parent != null) {
- builder.append(", parent=");
- builder.append(parent.getPackageName());
- builder.append(".");
- builder.append(parent.getName());
- } else {
- builder.append(", parent=null");
- }
- builder.append(", returnType=");
- builder.append(returnType);
- builder.append(", isFinal=");
- builder.append(isFinal);
- builder.append(", isReadOnly=");
- builder.append(isReadOnly);
- builder.append(", parameters=");
- builder.append(parameters);
- builder.append(", modifier=");
- builder.append(modifier);
- builder.append("]");
- return builder.toString();
- }
- }
-
- private static class GeneratedTransferObjectImpl implements
+ return new GeneratedTransferObjectImpl(null, getPackageName(), getName(), getComment(),
+ getAnnotations(), isAbstract(), extendsType, getImplementsTypes(), getEnclosedTypes(),
+ getEnclosedTransferObjects(), getConstants(), getEnumerations(), getMethodDefinitions(), properties,
+ equalsProperties, hashProperties, toStringProperties);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedTransferObject [packageName=");
+ builder.append(getPackageName());
+ builder.append(", name=");
+ builder.append(getName());
+ builder.append(", comment=");
+ builder.append(getComment());
+ builder.append(", constants=");
+ builder.append(getConstants());
+ builder.append(", enumerations=");
+ builder.append(getEnumerations());
+ builder.append(", properties=");
+ builder.append(properties);
+ builder.append(", equalsProperties=");
+ builder.append(equalsProperties);
+ builder.append(", hashCodeProperties=");
+ builder.append(hashProperties);
+ builder.append(", stringProperties=");
+ builder.append(toStringProperties);
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append(", methods=");
+ builder.append(getMethodDefinitions());
+ builder.append("]");
+ return builder.toString();
+ }
+
+ private static final class GeneratedTransferObjectImpl extends AbstractGeneratedType implements
GeneratedTransferObject {
- private final String packageName;
- private final String name;
- private final String comment;
- private final List<Constant> constants;
- private final List<Enumeration> enumerations;
private final List<GeneratedProperty> properties;
private final List<GeneratedProperty> equalsProperties;
private final List<GeneratedProperty> hashCodeProperties;
private final List<GeneratedProperty> stringProperties;
- private final List<AnnotationType> annotations;
- private final List<MethodSignature> methods;
private final GeneratedTransferObject extendsType;
- private final List<Type> implementsTypes;
- public GeneratedTransferObjectImpl(final String packageName,
- final String name, final String comment,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final GeneratedTransferObject extendsType,
- final List<Type> implementsTypes,
- final List<ConstantBuilder> constantBuilders,
- final List<EnumBuilder> enumBuilders,
- final List<MethodSignatureBuilder> methodBuilders,
- final List<GeneratedPropertyBuilder> propBuilers,
- final List<GeneratedPropertyBuilder> equalsBuilers,
- final List<GeneratedPropertyBuilder> hashCodeBuilers,
- final List<GeneratedPropertyBuilder> stringBuilers) {
- super();
- this.packageName = packageName;
- this.name = name;
- this.comment = comment;
- this.annotations = toUnmodifiableAnnotations(annotationBuilders);
+ GeneratedTransferObjectImpl(final Type parent,
+ final String packageName,
+ final String name, final String comment,
+ final List<AnnotationTypeBuilder> annotationBuilders,
+ final boolean isAbstract,
+ final GeneratedTransferObject extendsType,
+ final List<Type> implementsTypes,
+ final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+ final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+ final List<Constant> constants,
+ final List<EnumBuilder> enumBuilders,
+ final List<MethodSignatureBuilder> methodBuilders,
+ final List<GeneratedPropertyBuilder> propBuilders,
+ final List<GeneratedPropertyBuilder> equalsBuilders,
+ final List<GeneratedPropertyBuilder> hashCodeBuilders,
+ final List<GeneratedPropertyBuilder> stringBuilders) {
+ super(parent, packageName, name, comment, annotationBuilders, isAbstract, implementsTypes,
+ enclosedGenTypeBuilders,
+ enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
this.extendsType = extendsType;
- this.implementsTypes = Collections
- .unmodifiableList(implementsTypes);
- this.constants = toUnmodifiableConstant(constantBuilders);
- this.enumerations = toUnmodifiableEnumerations(enumBuilders);
- this.properties = toUnmodifiableProperties(propBuilers);
- this.methods = toUnmodifiableMethods(methodBuilders);
- this.equalsProperties = toUnmodifiableProperties(equalsBuilers);
- this.hashCodeProperties = toUnmodifiableProperties(hashCodeBuilers);
- this.stringProperties = toUnmodifiableProperties(stringBuilers);
- }
-
- private List<AnnotationType> toUnmodifiableAnnotations(
- final List<AnnotationTypeBuilder> annotationBuilders) {
- final List<AnnotationType> annotations = new ArrayList<AnnotationType>();
- for (final AnnotationTypeBuilder builder : annotationBuilders) {
- annotations.add(builder.toInstance());
- }
- return Collections.unmodifiableList(annotations);
- }
-
- private List<Enumeration> toUnmodifiableEnumerations(
- final List<EnumBuilder> enumBuilders) {
- final List<Enumeration> enumerations = new ArrayList<Enumeration>();
- for (final EnumBuilder builder : enumBuilders) {
- enumerations.add(builder.toInstance(this));
- }
- return Collections.unmodifiableList(enumerations);
- }
-
- private List<Constant> toUnmodifiableConstant(
- final List<ConstantBuilder> constBuilders) {
- final List<Constant> constants = new ArrayList<Constant>();
- for (final ConstantBuilder builder : constBuilders) {
- constants.add(builder.toInstance(this));
- }
- return Collections.unmodifiableList(constants);
- }
-
- private List<MethodSignature> toUnmodifiableMethods(
- final List<MethodSignatureBuilder> methodBuilders) {
- final List<MethodSignature> methods = new ArrayList<MethodSignature>();
- for (final MethodSignatureBuilder builder : methodBuilders) {
- methods.add(builder.toInstance(this));
- }
- return Collections.unmodifiableList(methods);
+ this.properties = toUnmodifiableProperties(propBuilders);
+ this.equalsProperties = toUnmodifiableProperties(equalsBuilders);
+ this.hashCodeProperties = toUnmodifiableProperties(hashCodeBuilders);
+ this.stringProperties = toUnmodifiableProperties(stringBuilders);
}
private List<GeneratedProperty> toUnmodifiableProperties(
final List<GeneratedPropertyBuilder> propBuilders) {
- final List<GeneratedProperty> constants = new ArrayList<GeneratedProperty>();
+ final List<GeneratedProperty> properties = new ArrayList<>();
for (final GeneratedPropertyBuilder builder : propBuilders) {
- constants.add(builder.toInstance(this));
+ properties.add(builder.toInstance(this));
}
- return Collections.unmodifiableList(constants);
- }
-
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Type getParentType() {
- return null;
- }
-
- @Override
- public String getComment() {
- return comment;
- }
-
- @Override
- public List<AnnotationType> getAnnotations() {
- return annotations;
- }
-
- @Override
- public List<Type> getImplements() {
- return implementsTypes;
+ return Collections.unmodifiableList(properties);
}
@Override
return extendsType;
}
- @Override
- public List<Enumeration> getEnumDefintions() {
- return enumerations;
- }
-
- @Override
- public List<Constant> getConstantDefinitions() {
- return constants;
- }
-
- @Override
- public List<MethodSignature> getMethodDefinitions() {
- return methods;
- }
-
@Override
public List<GeneratedProperty> getProperties() {
return properties;
return stringProperties;
}
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result
- + ((packageName == null) ? 0 : packageName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- GeneratedTransferObjectImpl other = (GeneratedTransferObjectImpl) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (packageName == null) {
- if (other.packageName != null) {
- return false;
- }
- } else if (!packageName.equals(other.packageName)) {
- return false;
- }
- return true;
- }
-
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GeneratedTransferObject [packageName=");
- builder.append(packageName);
+ builder.append(getPackageName());
builder.append(", name=");
- builder.append(name);
+ builder.append(getName());
builder.append(", comment=");
- builder.append(comment);
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append(getComment());
+ builder.append(", extends=");
+ builder.append(getExtends());
+ builder.append(", implements=");
+ builder.append(getImplements());
+ builder.append(", enclosedTypes=");
+ builder.append(getEnclosedTypes());
builder.append(", constants=");
- builder.append(constants);
+ builder.append(getConstantDefinitions());
builder.append(", enumerations=");
- builder.append(enumerations);
+ builder.append(getEnumerations());
builder.append(", properties=");
builder.append(properties);
builder.append(", equalsProperties=");
builder.append(hashCodeProperties);
builder.append(", stringProperties=");
builder.append(stringProperties);
- builder.append(", annotations=");
- builder.append(annotations);
builder.append(", methods=");
- builder.append(methods);
+ builder.append(getMethodDefinitions());
builder.append("]");
return builder.toString();
}
}
-
- private static final class GeneratedTransferIdentityObjectImpl extends
- GeneratedTransferObjectImpl implements
- GeneratedTransferIdentityObject {
- public GeneratedTransferIdentityObjectImpl(final String packageName,
- final String name, final String comment,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final GeneratedTransferObject extendsType,
- final List<Type> implementsTypes,
- final List<ConstantBuilder> constantBuilders,
- final List<EnumBuilder> enumBuilders,
- final List<MethodSignatureBuilder> methodBuilders,
- final List<GeneratedPropertyBuilder> propBuilers,
- final List<GeneratedPropertyBuilder> equalsBuilers,
- final List<GeneratedPropertyBuilder> hashCodeBuilers,
- final List<GeneratedPropertyBuilder> stringBuilers) {
- super(packageName, name, comment, annotationBuilders, extendsType,
- implementsTypes, constantBuilders, enumBuilders,
- methodBuilders, propBuilers, equalsBuilers,
- hashCodeBuilers, stringBuilers);
- }
- }
}
*/
package org.opendaylight.controller.binding.generator.util.generated.type.builder;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
-
-public final class GeneratedTypeBuilderImpl implements GeneratedTypeBuilder {
-
- private final String packageName;
- private String comment = "";
- private final String name;
- private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
- private final List<Type> implementsTypes = new ArrayList<Type>();
- private final List<EnumBuilder> enumDefinitions = new ArrayList<EnumBuilder>();
- private final List<ConstantBuilder> constantDefintions = new ArrayList<ConstantBuilder>();
- private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<MethodSignatureBuilder>();
-
- public GeneratedTypeBuilderImpl(final String packageName, final String name) {
- this.packageName = packageName;
- this.name = name;
- }
-
- @Override
- public Type getParentType() {
- return this;
- }
-
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public void addComment(String comment) {
- this.comment = comment;
- }
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
- @Override
- public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
- if (packageName != null && name != null) {
- final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
- packageName, name);
- if (annotationBuilders.add(builder)) {
- return builder;
- }
- }
- return null;
- }
+import java.util.List;
- @Override
- public ConstantBuilder addConstant(Type type, String name, Object value) {
- final ConstantBuilder builder = new ConstantBuilderImpl(type, name,
- value);
- constantDefintions.add(builder);
- return builder;
- }
+public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder {
- @Override
- public EnumBuilder addEnumeration(final String name) {
- final String innerPackageName = packageName + "." + this.name;
- final EnumBuilder builder = new EnumerationBuilderImpl(
- innerPackageName, name);
- enumDefinitions.add(builder);
- return builder;
+ public GeneratedTypeBuilderImpl(String packageName, String name) {
+ super(packageName, name);
+ setAbstract(true);
}
@Override
- public MethodSignatureBuilder addMethod(final String name) {
- final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(
- this, name);
- methodDefinitions.add(builder);
- return builder;
+ public GeneratedType toInstance() {
+ return new GeneratedTypeImpl(null, getPackageName(), getName(), getComment(), getAnnotations(), isAbstract(),
+ getImplementsTypes(), getEnclosedTypes(), getEnclosedTransferObjects(), getEnumerations(),
+ getConstants(), getMethodDefinitions());
}
@Override
- public boolean addImplementsType(final Type genType) {
- if (genType != null) {
- return implementsTypes.add(genType);
- }
- return false;
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("GeneratedTransferObject [packageName=");
+ builder.append(getPackageName());
+ builder.append(", name=");
+ builder.append(getName());
+ builder.append(", comment=");
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append(getComment());
+ builder.append(", implements=");
+ builder.append(getImplementsTypes());
+ builder.append(", enclosedTypes=");
+ builder.append(getEnclosedTypes());
+ builder.append(", constants=");
+ builder.append(getConstants());
+ builder.append(", enumerations=");
+ builder.append(getEnumerations());
+ builder.append(", properties=");
+ builder.append(", methods=");
+ builder.append(getMethodDefinitions());
+ builder.append("]");
+ return builder.toString();
}
-
- @Override
- public GeneratedType toInstance() {
- return new GeneratedTypeImpl(this, packageName, name, comment,
- annotationBuilders, implementsTypes, enumDefinitions, constantDefintions,
- methodDefinitions);
- }
-
- private static final class GeneratedTypeImpl implements GeneratedType {
-
- private final Type parent;
- private final String packageName;
- private final String name;
- private final String comment;
- private final List<AnnotationType> annotations;
- private final List<Type> implementsTypes;
- private final List<Enumeration> enumDefinitions;
- private final List<Constant> constantDefintions;
- private final List<MethodSignature> methodDefinitions;
-
- public GeneratedTypeImpl(final Type parent, final String packageName,
- final String name, final String comment,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final List<Type> implementsTypes,
- final List<EnumBuilder> enumBuilders,
- final List<ConstantBuilder> constantBuilders,
- final List<MethodSignatureBuilder> methodBuilders) {
- super();
- this.parent = parent;
- this.packageName = packageName;
- this.name = name;
- this.comment = comment;
- this.annotations = toUnmodifiableAnnotations(annotationBuilders);
- this.implementsTypes = Collections.unmodifiableList(implementsTypes);
- this.constantDefintions = toUnmodifiableConstants(constantBuilders);
- this.enumDefinitions = toUnmodifiableEnums(enumBuilders);
- this.methodDefinitions = toUnmodifiableMethods(methodBuilders);
- }
-
- private List<AnnotationType> toUnmodifiableAnnotations(
- final List<AnnotationTypeBuilder> annotationBuilders) {
- final List<AnnotationType> annotations = new ArrayList<AnnotationType>();
- for (final AnnotationTypeBuilder builder : annotationBuilders) {
- annotations.add(builder.toInstance());
- }
- return Collections.unmodifiableList(annotations);
- }
-
- private List<MethodSignature> toUnmodifiableMethods(
- List<MethodSignatureBuilder> methodBuilders) {
- final List<MethodSignature> methods = new ArrayList<MethodSignature>();
- for (final MethodSignatureBuilder methodBuilder : methodBuilders) {
- methods.add(methodBuilder.toInstance(this));
- }
- return Collections.unmodifiableList(methods);
- }
-
- private List<Enumeration> toUnmodifiableEnums(
- List<EnumBuilder> enumBuilders) {
- final List<Enumeration> enums = new ArrayList<Enumeration>();
- for (final EnumBuilder enumBuilder : enumBuilders) {
- enums.add(enumBuilder.toInstance(this));
- }
- return Collections.unmodifiableList(enums);
- }
-
- private List<Constant> toUnmodifiableConstants(
- List<ConstantBuilder> constantBuilders) {
- final List<Constant> constants = new ArrayList<Constant>();
- for (final ConstantBuilder enumBuilder : constantBuilders) {
- constants.add(enumBuilder.toInstance(this));
- }
- return Collections.unmodifiableList(constants);
- }
-
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Type getParentType() {
- return parent;
- }
-
- @Override
- public String getComment() {
- return comment;
- }
-
- @Override
- public List<AnnotationType> getAnnotations() {
- return annotations;
- }
-
- @Override
- public List<Type> getImplements() {
- return implementsTypes;
- }
-
- @Override
- public List<Enumeration> getEnumDefintions() {
- return enumDefinitions;
- }
-
- @Override
- public List<Constant> getConstantDefinitions() {
- return constantDefintions;
- }
-
- @Override
- public List<MethodSignature> getMethodDefinitions() {
- return methodDefinitions;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime
- * result
- + ((constantDefintions == null) ? 0 : constantDefintions
- .hashCode());
- result = prime
- * result
- + ((enumDefinitions == null) ? 0 : enumDefinitions
- .hashCode());
- result = prime
- * result
- + ((methodDefinitions == null) ? 0 : methodDefinitions
- .hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result
- + ((packageName == null) ? 0 : packageName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- GeneratedTypeImpl other = (GeneratedTypeImpl) obj;
- if (constantDefintions == null) {
- if (other.constantDefintions != null) {
- return false;
- }
- } else if (!constantDefintions.equals(other.constantDefintions)) {
- return false;
- }
- if (enumDefinitions == null) {
- if (other.enumDefinitions != null) {
- return false;
- }
- } else if (!enumDefinitions.equals(other.enumDefinitions)) {
- return false;
- }
- if (methodDefinitions == null) {
- if (other.methodDefinitions != null) {
- return false;
- }
- } else if (!methodDefinitions.equals(other.methodDefinitions)) {
- return false;
- }
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (packageName == null) {
- if (other.packageName != null) {
- return false;
- }
- } else if (!packageName.equals(other.packageName)) {
- return false;
- }
- return true;
- }
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("GeneratedType [packageName=");
- builder.append(packageName);
- builder.append(", name=");
- builder.append(name);
- if (parent != null) {
- builder.append(", parent=");
- builder.append(parent.getPackageName());
- builder.append(".");
- builder.append(parent.getName());
- } else {
- builder.append(", parent=null");
- }
- builder.append(", comment=");
- builder.append(comment);
- builder.append(", annotations=");
- builder.append(annotations);
- builder.append(", enumDefinitions=");
- builder.append(enumDefinitions);
- builder.append(", constantDefintions=");
- builder.append(constantDefintions);
- builder.append(", methodDefinitions=");
- builder.append(methodDefinitions);
- builder.append("]");
- return builder.toString();
+ private static final class GeneratedTypeImpl extends AbstractGeneratedType {
+
+ public GeneratedTypeImpl(final Type parent, final String packageName, final String name, final String comment,
+ final List<AnnotationTypeBuilder> annotationBuilders, final boolean isAbstract,
+ final List<Type> implementsTypes,
+ final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+ final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+ final List<EnumBuilder> enumBuilders, final List<Constant> constants,
+ final List<MethodSignatureBuilder> methodBuilders) {
+ super(parent, packageName, name, comment, annotationBuilders, isAbstract, implementsTypes,
+ enclosedGenTypeBuilders, enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
}
}
}
+/*
+ * 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.binding.generator.util.generated.type.builder;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
import org.opendaylight.controller.sal.binding.model.api.Type;
import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
-final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
- private final String name;
- private Type returnType;
+final class MethodSignatureBuilderImpl extends AbstractTypeMemberBuilder implements MethodSignatureBuilder {
+
private final List<MethodSignature.Parameter> parameters;
- private final List<AnnotationTypeBuilder> annotationBuilders;
- private String comment = "";
- private final Type parent;
+ private boolean isAbstract;
- public MethodSignatureBuilderImpl(final Type parent, final String name) {
- super();
- this.name = name;
- this.parent = parent;
- this.parameters = new ArrayList<MethodSignature.Parameter>();
- this.annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
+ public MethodSignatureBuilderImpl(final String name) {
+ super(name);
+ this.parameters = new ArrayList<>();
}
@Override
- public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
- if (packageName != null && name != null) {
- final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
- packageName, name);
- if (annotationBuilders.add(builder)) {
- return builder;
- }
- }
- return null;
- }
-
- @Override
- public void addReturnType(Type returnType) {
- if (returnType != null) {
- this.returnType = returnType;
- }
+ public void setAbstract(boolean isAbstract) {
+ this.isAbstract = isAbstract;
}
@Override
parameters.add(new MethodParameterImpl(name, type));
}
- @Override
- public void addComment(String comment) {
- this.comment = comment;
- }
-
@Override
public MethodSignature toInstance(Type definingType) {
- return new MethodSignatureImpl(definingType, name, annotationBuilders,
- comment, returnType, parameters);
+ final List<AnnotationType> annotations = toAnnotationTypes();
+ return new MethodSignatureImpl(definingType, getName(), annotations,
+ getComment(), getAccessModifier(), getReturnType(), parameters, isFinal(), isAbstract);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result
+ ((parameters == null) ? 0 : parameters.hashCode());
result = prime * result
- + ((returnType == null) ? 0 : returnType.hashCode());
+ + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
return result;
}
return false;
}
MethodSignatureBuilderImpl other = (MethodSignatureBuilderImpl) obj;
- if (name == null) {
- if (other.name != null) {
+ if (getName() == null) {
+ if (other.getName() != null) {
return false;
}
- } else if (!name.equals(other.name)) {
+ } else if (!getName().equals(other.getName())) {
return false;
}
if (parameters == null) {
} else if (!parameters.equals(other.parameters)) {
return false;
}
- if (returnType == null) {
- if (other.returnType != null) {
+ if (getReturnType() == null) {
+ if (other.getReturnType() != null) {
return false;
}
- } else if (!returnType.equals(other.returnType)) {
+ } else if (!getReturnType().equals(other.getReturnType())) {
return false;
}
return true;
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MethodSignatureBuilderImpl [name=");
- builder.append(name);
+ builder.append(getName());
builder.append(", returnType=");
- builder.append(returnType);
+ builder.append(getReturnType());
builder.append(", parameters=");
builder.append(parameters);
builder.append(", annotationBuilders=");
- builder.append(annotationBuilders);
+ builder.append(getAnnotationBuilders());
builder.append(", comment=");
- builder.append(comment);
- if (parent != null) {
- builder.append(", parent=");
- builder.append(parent.getPackageName());
- builder.append(".");
- builder.append(parent.getName());
- } else {
- builder.append(", parent=null");
- }
+ builder.append(getComment());
builder.append("]");
return builder.toString();
}
-
- private static final class MethodSignatureImpl implements MethodSignature {
-
- private final String name;
- private final String comment;
- private final Type definingType;
- private final Type returnType;
- private final List<Parameter> params;
- private List<AnnotationType> annotations;
-
- public MethodSignatureImpl(final Type definingType, final String name,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final String comment, final Type returnType,
- final List<Parameter> params) {
- super();
- this.name = name;
- this.comment = comment;
- this.definingType = definingType;
- this.returnType = returnType;
- this.params = Collections.unmodifiableList(params);
-
- this.annotations = new ArrayList<AnnotationType>();
- for (final AnnotationTypeBuilder builder : annotationBuilders) {
- this.annotations.add(builder.toInstance());
- }
- this.annotations = Collections.unmodifiableList(this.annotations);
- }
-
- @Override
- public List<AnnotationType> getAnnotations() {
- return annotations;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public String getComment() {
- return comment;
- }
-
- @Override
- public Type getDefiningType() {
- return definingType;
- }
-
- @Override
- public Type getReturnType() {
- return returnType;
- }
-
- @Override
- public List<Parameter> getParameters() {
- return params;
- }
-
- @Override
- public AccessModifier getAccessModifier() {
- return AccessModifier.PUBLIC;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result
- + ((params == null) ? 0 : params.hashCode());
- result = prime * result
- + ((returnType == null) ? 0 : returnType.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- MethodSignatureImpl other = (MethodSignatureImpl) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (params == null) {
- if (other.params != null) {
- return false;
- }
- } else if (!params.equals(other.params)) {
- return false;
- }
- if (returnType == null) {
- if (other.returnType != null) {
- return false;
- }
- } else if (!returnType.equals(other.returnType)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("MethodSignatureImpl [name=");
- builder.append(name);
- builder.append(", comment=");
- builder.append(comment);
- if (definingType != null) {
- builder.append(", definingType=");
- builder.append(definingType.getPackageName());
- builder.append(".");
- builder.append(definingType.getName());
- } else {
- builder.append(", definingType= null");
- }
- builder.append(", returnType=");
- builder.append(returnType);
- builder.append(", params=");
- builder.append(params);
- builder.append(", annotations=");
- builder.append(annotations);
- builder.append("]");
- return builder.toString();
- }
- }
}
\ 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.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+import java.util.Collections;
+import java.util.List;
+
+class MethodSignatureImpl extends AbstractTypeMember implements MethodSignature {
+
+ private final List<Parameter> params;
+ private final boolean isAbstract;
+
+ public MethodSignatureImpl(final Type definingType, final String name,
+ final List<AnnotationType> annotations,
+ final String comment, final AccessModifier accessModifier,
+ final Type returnType, final List<Parameter> params, boolean isFinal,
+ boolean isAbstract) {
+ super(definingType, name, annotations, comment, accessModifier, returnType, isFinal);
+ this.params = Collections.unmodifiableList(params);
+ this.isAbstract = isAbstract;
+ }
+
+ @Override
+ public boolean isAbstract() {
+ return isAbstract;
+ }
+
+ @Override
+ public List<Parameter> getParameters() {
+ return params;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+ result = prime * result
+ + ((params == null) ? 0 : params.hashCode());
+ result = prime * result
+ + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ MethodSignatureImpl other = (MethodSignatureImpl) obj;
+ if (getName() == null) {
+ if (other.getName() != null) {
+ return false;
+ }
+ } else if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (params == null) {
+ if (other.params != null) {
+ return false;
+ }
+ } else if (!params.equals(other.params)) {
+ return false;
+ }
+ if (getReturnType() == null) {
+ if (other.getReturnType() != null) {
+ return false;
+ }
+ } else if (!getReturnType().equals(other.getReturnType())) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("MethodSignatureImpl [name=");
+ builder.append(getName());
+ builder.append(", comment=");
+ builder.append(getComment());
+ if (getDefiningType() != null) {
+ builder.append(", definingType=");
+ builder.append(getDefiningType().getPackageName());
+ builder.append(".");
+ builder.append(getDefiningType().getName());
+ } else {
+ builder.append(", definingType= null");
+ }
+ builder.append(", returnType=");
+ builder.append(getReturnType());
+ builder.append(", params=");
+ builder.append(params);
+ builder.append(", annotations=");
+ builder.append(getAnnotations());
+ builder.append("]");
+ return builder.toString();
+ }
+}
import org.junit.Test;
import org.opendaylight.controller.binding.generator.util.Types;
-import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
final MethodSignatureBuilder methodBuilder = genTypeBuilder
.addMethod("simpleMethod");
- methodBuilder.addReturnType(Types.typeForClass(Integer.class));
+ methodBuilder.setReturnType(Types.typeForClass(Integer.class));
final AnnotationTypeBuilder annotManAttr = methodBuilder
.addAnnotation("org.springframework.jmx.export.annotation",
"ManagedAttribute");
final GeneratedPropertyBuilder propertyBuilder = genTOBuilder
.addProperty("simpleProperty");
- propertyBuilder.addReturnType(Types.typeForClass(Integer.class));
+ propertyBuilder.setReturnType(Types.typeForClass(Integer.class));
final AnnotationTypeBuilder annotManAttr = propertyBuilder
.addAnnotation("org.springframework.jmx.export.annotation",
"ManagedAttribute");
@Override
public Writer generate(Type type) throws IOException {
final Writer writer = new StringWriter();
- boolean isIdentity = type instanceof GeneratedTransferIdentityObject;
if (type instanceof GeneratedTransferObject) {
GeneratedTransferObject genTO = (GeneratedTransferObject) type;
final String currentPkg = genTO.getPackageName();
final List<GeneratedProperty> fields = genTO.getProperties();
- final List<Enumeration> enums = genTO.getEnumDefintions();
+ final List<Enumeration> enums = genTO.getEnumerations();
writer.write(GeneratorUtil.createPackageDeclaration(currentPkg));
writer.write(NL);
writer.write(NL);
writer.write(GeneratorUtil.createClassDeclaration(genTO, "",
- imports, isIdentity));
+ imports, genTO.isAbstract()));
writer.write(NL);
writer.write(NL);
}
writer.write(NL);
writer.write(GeneratorUtil.createConstructor(genTO, TAB,
- imports, isIdentity) + NL);
+ imports, genTO.isAbstract()) + NL);
writer.write(NL);
for (GeneratedProperty field : fields) {
writer.write(GeneratorUtil.createGetter(field, TAB,
final String genTypePkg = genType.getPackageName();
final List<Constant> constants = genType.getConstantDefinitions();
- final List<MethodSignature> methods = genType.getMethodDefinitions();
+ final List<MethodSignature> methods = genType.getMethodDefinitions();
List<Type> impl = genType.getImplements();
// IMPLEMENTATIONS
final List<Constant> constants = genType.getConstantDefinitions();
final List<MethodSignature> methods = genType
.getMethodDefinitions();
- final List<Enumeration> enums = genType.getEnumDefintions();
+ final List<Enumeration> enums = genType.getEnumerations();
writer.write(GeneratorUtil.createPackageDeclaration(genType
.getPackageName()));
}
return writer;
}
-
}
"simple.pack", "DefCtor");
GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
- propBuilder.addReturnType(Types.typeForClass(String.class));
+ propBuilder.setReturnType(Types.typeForClass(String.class));
propBuilder.setReadOnly(false);
propBuilder = toBuilder.addProperty("bar");
- propBuilder.addReturnType(Types.typeForClass(Integer.class));
+ propBuilder.setReturnType(Types.typeForClass(Integer.class));
propBuilder.setReadOnly(false);
final GeneratedTransferObject genTO = toBuilder.toInstance();
"simple.pack", "DefCtor");
GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
- propBuilder.addReturnType(Types.typeForClass(String.class));
+ propBuilder.setReturnType(Types.typeForClass(String.class));
propBuilder.setReadOnly(false);
toBuilder.addToStringProperty(propBuilder);
propBuilder = toBuilder.addProperty("bar");
- propBuilder.addReturnType(Types.typeForClass(Integer.class));
+ propBuilder.setReturnType(Types.typeForClass(Integer.class));
propBuilder.setReadOnly(false);
toBuilder.addToStringProperty(propBuilder);
final GeneratedTransferObject genTO = toBuilder.toInstance();
*/\r
package org.opendaylight.controller.sal.binding.model.api;\r
\r
+/**\r
+ * Enum definition which provides four access modifiers that are described\r
+ * in Java programming language (Default, Private, Protected, Public).\r
+ */\r
public enum AccessModifier {\r
- PRIVATE, PUBLIC, PROTECTED\r
+ DEFAULT, PRIVATE, PUBLIC, PROTECTED\r
}\r
import java.util.List;
-
+/**
+ * The Annotation Type interface is designed to hold information about
+ * annotation for any type that could be annotated in Java.
+ * <br>
+ * For sake of simplicity the Annotation Type is not designed to model exact
+ * behaviour of annotation mechanism, but just to hold information needed to
+ * model annotation over java Type definition.
+ */
public interface AnnotationType extends Type {
-
+
+ /**
+ * Returns the List of Annotations.
+ * <br>
+ * Each Annotation Type MAY have defined multiple Annotations.
+ *
+ * @return the List of Annotations.
+ */
public List<AnnotationType> getAnnotations();
-
+
+ /**
+ * Returns Parameter Definition assigned for given parameter name.
+ * <br>
+ * If Annotation does not contain parameter with specified param name,
+ * the method MAY return <code>null</code> value.
+ *
+ * @param paramName Parameter Name
+ * @return Parameter Definition assigned for given parameter name.
+ */
public Parameter getParameter(final String paramName);
-
+
+ /**
+ * Returns List of all parameters assigned to Annotation Type.
+ *
+ * @return List of all parameters assigned to Annotation Type.
+ */
public List<Parameter> getParameters();
-
+
+ /**
+ * Returns List of parameter names.
+ *
+ * @return List of parameter names.
+ */
public List<String> getParameterNames();
-
+
+ /**
+ * Returns <code>true</code> if annotation contains parameters.
+ *
+ * @return <code>true</code> if annotation contains parameters.
+ */
public boolean containsParameters();
-
+
+ /**
+ * Annotation Type parameter interface. For simplicity the Parameter
+ * contains values and value types as Strings. Every annotation which
+ * contains parameters could contain either single parameter or array of
+ * parameters. To model this purposes the by contract if the parameter
+ * contains single parameter the {@link #getValues()} method will return
+ * empty List and {@link #getValue()} MUST always return non-<code>null</code>
+ * parameter. If the Parameter holds List of values the singular {@link
+ * #getValue()} parameter MAY return <code>null</code> value.
+ */
interface Parameter {
-
+
+ /**
+ * Returns the Name of the parameter.
+ *
+ * @return the Name of the parameter.
+ */
public String getName();
-
+
+ /**
+ * Returns value in String format if Parameter contains singular value,
+ * otherwise MAY return <code>null</code>.
+ *
+ * @return value in String format if Parameter contains singular value.
+ */
public String getValue();
-
+
+ /**
+ * Returns List of Parameter assigned values in order in which they
+ * were assigned for given parameter name.
+ * <br>
+ * If there are multiple values assigned for given parameter name the
+ * method MUST NOT return empty List.
+ *
+ * @return List of Parameter assigned values in order in which they
+ * were assigned for given parameter name.
+ */
public List<String> getValues();
}
}
import java.io.IOException;\r
import java.io.Writer;\r
\r
+/**\r
+ *\r
+ *\r
+ */\r
public interface CodeGenerator {\r
\r
+ /**\r
+ *\r
+ * @param type\r
+ * @return\r
+ * @throws IOException\r
+ */\r
Writer generate(Type type) throws IOException;\r
\r
}\r
*/
package org.opendaylight.controller.sal.binding.model.api;
+/**
+ * The Concrete Type is marker interface that encapsulates definition of java
+ * concrete type.
+ */
public interface ConcreteType extends Type {
}
*/\r
package org.opendaylight.controller.sal.binding.model.api;\r
\r
+/**\r
+ * Interface Contact is designed to hold and model java constant. In Java\r
+ * there are no constant keywords instead of the constant is defined as\r
+ * static final field with assigned value. For this purpose the Constant\r
+ * interface contains methods {@link #getType()} to provide wrapped return\r
+ * Type of Constant, {@link #getName()} the Name of constant and the {@link\r
+ * #getValue()} for providing of value assigned to Constant. To determine of\r
+ * which type the constant value is it is recommended firstly to retrieve\r
+ * Type from constant. The Type interface holds base information like java\r
+ * package name and java type name (e.g. fully qualified name). From this\r
+ * string user should be able to determine to which type can be {@link\r
+ * #getValue()} type typecasted to unbox and provide value assigned to\r
+ * constant.\r
+ */\r
public interface Constant {\r
\r
+ /**\r
+ * Returns the Type that declares constant.\r
+ *\r
+ * @return the Type that declares constant.\r
+ */\r
public Type getDefiningType();\r
\r
+ /**\r
+ * Returns the return Type (or just Type) of the Constant.\r
+ *\r
+ * @return the return Type (or just Type) of the Constant.\r
+ */\r
public Type getType();\r
\r
+ /**\r
+ * Returns the name of constant.\r
+ * <br>\r
+ * By conventions the name SHOULD be in CAPITALS separated with\r
+ * underscores.\r
+ *\r
+ * @return the name of constant.\r
+ */\r
public String getName();\r
\r
+ /**\r
+ * Returns boxed value that is assigned for context.\r
+ *\r
+ * @return boxed value that is assigned for context.\r
+ */\r
public Object getValue();\r
\r
+ /**\r
+ * Returns Constant definition in formatted string.\r
+ * <br>\r
+ * <br>\r
+ * The expected string SHOULD be in format: <code>public final\r
+ * static [Type] CONSTANT_NAME = [value];</code>\r
+ *\r
+ * @return Constant definition in formatted string.\r
+ */\r
public String toFormattedString();\r
}\r
import java.util.List;
+/**
+ *
+ */
public interface Enumeration extends Type {
-
+
+ /**
+ *
+ * @return
+ */
public List<AnnotationType> getAnnotations();
-
+
+ /**
+ *
+ * @return
+ */
public Type getDefiningType();
+ /**
+ *
+ * @return
+ */
public List<Pair> getValues();
+ /**
+ *
+ * @return
+ */
public String toFormattedString();
+ /**
+ *
+ */
interface Pair {
public String getName();
*/\r
package org.opendaylight.controller.sal.binding.model.api;\r
\r
-public interface GeneratedProperty extends MethodSignature {\r
+/**\r
+ * Generated Property extends interface {@link MethodSignature} interface.\r
+ * <br>\r
+ * The Generated Property interface is designed to store information of\r
+ * fields (or members) declared in Java Transfer Objects (or any java\r
+ * classes) and their access counterparts (getters and setters).\r
+ *\r
+ * @see MethodSignature\r
+ */\r
+public interface GeneratedProperty extends TypeMember {\r
\r
+ /**\r
+ * Returns <code>true</code> if the property si declared as read-only.\r
+ * <br>\r
+ * If the property has flag <code>isReadOnly == true</code> the property\r
+ * SHOULD be generated as getter only.\r
+ *\r
+ * @return <code>true</code> if the property si declared as read-only.\r
+ */\r
public boolean isReadOnly();\r
-\r
- public boolean isFinal();\r
}\r
import java.util.List;
+/**
+ * Generated Transfer Object extends {@link GeneratedType} and is designed to
+ * represent Java Class. The Generated Transfer Object contains declarations
+ * of member fields stored in List of Properties. The Generated Transfer
+ * Object can be extended by exactly ONE Generated Transfer Object as Java
+ * don't allow multiple inheritance. For retrieval of implementing Generated
+ * Types use {@link #getImplements()} method.
+ * <br>
+ * Every transfer object SHOULD contain equals, hashCode and toString definitions.
+ * For this purpose retrieve definitions through {@link #getEqualsIdentifiers
+ * ()}, {@link #getHashCodeIdentifiers()} and {@link #getToStringIdentifiers
+ * ()}.
+ *
+ */
public interface GeneratedTransferObject extends GeneratedType {
-
+
+ /**
+ * Returns the extending Generated Transfer Object or <code>null</code>
+ * if there is no extending Generated Transfer Object.
+ *
+ * @return the extending Generated Transfer Object or <code>null</code>
+ * if there is no extending Generated Transfer Object.
+ */
public GeneratedTransferObject getExtends();
-
+
+ /**
+ * Returns List of Properties that are declared for Generated Transfer
+ * Object.
+ *
+ * @return List of Properties that are declared for Generated Transfer
+ * Object.
+ */
public List<GeneratedProperty> getProperties();
-
+
+ /**
+ * Returns List of Properties that are designated to define equality for
+ * Generated Transfer Object.
+ *
+ * @return List of Properties that are designated to define equality for
+ * Generated Transfer Object.
+ */
public List<GeneratedProperty> getEqualsIdentifiers();
-
+
+ /**
+ * Returns List of Properties that are designated to define identity for
+ * Generated Transfer Object.
+ *
+ * @return List of Properties that are designated to define identity for
+ * Generated Transfer Object.
+ */
public List<GeneratedProperty> getHashCodeIdentifiers();
-
+
+ /**
+ * Returns List of Properties that will be members of toString definition
+ * for Generated Transfer Object.
+ *
+ * @return List of Properties that will be members of toString definition
+ * for Generated Transfer Object.
+ */
public List<GeneratedProperty> getToStringIdentifiers();
}
* <li><code>interface</code> name (with commentary that <b>SHOULD</b> be
* present to proper define interface and base <i>contracts</i> specified for
* interface)</li>
+ * <li>Each Generated Type can define list of types that Generated Type
+ * can implement to extend it's definition (i.e. interface extends list of
+ * interfaces or java class implements list of interfaces)</li>
+ * <li>Each Generated Type can contain multiple enclosed definitions of
+ * Generated Types (i.e. interface can contain N enclosed interface
+ * definitions or enclosed classes)</li>
* <li><code>enum</code> and <code>constant</code> definitions (i.e. each
* constant definition is by default defined as <code>public static final</code>
* + type (either primitive or object) and constant name</li>
* types) and return values</li>
* </ul>
*
- * By the definition of the interface constant, enum and method definitions MUST
+ * By the definition of the interface constant, enum,
+ * enclosed types and method definitions MUST
* be public, so there is no need to specify the scope of visibility.
- *
- *
*/
public interface GeneratedType extends Type {
+ /**
+ * Returns the parent type if Generated Type is defined as enclosing type,
+ * otherwise returns <code>null</code>
+ *
+ * @return the parent type if Generated Type is defined as enclosing type,
+ * otherwise returns <code>null</code>
+ */
public Type getParentType();
-
+
+ /**
+ * Returns comment string associated with Generated Type.
+ *
+ * @return comment string associated with Generated Type.
+ */
public String getComment();
-
+
+ /**
+ * Returns List of annotation definitions associated with generated type.
+ *
+ * @return List of annotation definitions associated with generated type.
+ */
public List<AnnotationType> getAnnotations();
-
+
+ /**
+ * Returns <code>true</code> if The Generated Type is defined as abstract.
+ *
+ * @return <code>true</code> if The Generated Type is defined as abstract.
+ */
+ public boolean isAbstract();
+
+ /**
+ * Returns List of Types that Generated Type will implement.
+ *
+ * @return List of Types that Generated Type will implement.
+ */
public List<Type> getImplements();
-
+
/**
- * Returns Set of all Enumerator definitions associated with interface.
- *
- * @return Set of all Enumerator definitions associated with interface.
+ * Returns List of enclosing Generated Types.
+ *
+ * @return List of enclosing Generated Types.
*/
- public List<Enumeration> getEnumDefintions();
+ public List<GeneratedType> getEnclosedTypes();
/**
+ * Returns List of all Enumerator definitions associated with Generated
+ * Type.
*
- *
- * @return
+ * @return List of all Enumerator definitions associated with Generated
+ * Type.
+ */
+ public List<Enumeration> getEnumerations();
+
+ /**
+ * Returns List of Constant definitions associated with Generated Type.
+ *
+ * @return List of Constant definitions associated with Generated Type.
*/
public List<Constant> getConstantDefinitions();
/**
+ * Returns List of Method Definitions associated with Generated Type.
*
- *
- * @return
+ * @return List of Method Definitions associated with Generated Type.
*/
public List<MethodSignature> getMethodDefinitions();
-
}
import java.util.List;
-public interface MethodSignature {
-
- public List<AnnotationType> getAnnotations();
-
- public String getName();
-
- public String getComment();
-
- public Type getDefiningType();
+/**
+ * The Method Signature interface contains simplified meta model for java
+ * method definition. Each method MUST be defined by name, return type,
+ * parameters and access modifier.
+ * <br>
+ * Additionally method MAY contain associated annotations and comment. By
+ * contract if method does not contain any comments or annotation definitions
+ * the {@link #getComment()} SHOULD rather return empty string and {@link
+ * #getAnnotations()} SHOULD rather return empty list than <code>null</code>
+ * values.
+ * <br>
+ * The defining Type contains the reference to Generated Type that declares
+ * Method Signature.
+ */
+public interface MethodSignature extends TypeMember {
- public Type getReturnType();
+ /**
+ * Returns <code>true</code> if the method signature is defined as abstract.
+ * <br>
+ * By default in java all method declarations in interface are defined as abstract,
+ * but the user don't need necessary to declare abstract keyword in front of each method.
+ * <br>
+ * The abstract methods are allowed in Class definitions but only when the class is declared as abstract.
+ *
+ * @return <code>true</code> if the method signature is defined as abstract.
+ */
+ public boolean isAbstract();
+ /**
+ * Returns the List of parameters that method declare. If the method does
+ * not contain any parameters, the method will return empty List.
+ *
+ * @return the List of parameters that method declare.
+ */
public List<Parameter> getParameters();
- public AccessModifier getAccessModifier();
-
+ /**
+ * The Parameter interface is designed to hold the information of method
+ * Parameter(s). The parameter is defined by his Name which MUST be
+ * unique as java does not allow multiple parameters with same names for
+ * one method and Type that is associated with parameter.
+ */
interface Parameter {
+
+ /**
+ * Returns the parameter name.
+ *
+ * @return the parameter name.
+ */
public String getName();
+ /**
+ * Returns Type that is bounded to parameter name.
+ *
+ * @return Type that is bounded to parameter name.
+ */
public Type getType();
}
}
\r
/**\r
* Represents an instance of simple parametrized type such as List<String>.\r
+ *\r
+ * The parametrized Type is designed to be used to store information of Java\r
+ * Generic Type. The array of {@link #getActualTypeArguments()} holds\r
+ * information of all generic parameters defined for Parameterized Type.\r
*/\r
public interface ParameterizedType extends Type {\r
\r
+ /**\r
+ * Returns array of Types that are defined for Parameterized Type.\r
+ * <br>\r
+ * (for example if ParameterizedType encapsulates java generic Map that\r
+ * specifies two parameters Map<K,V> and the K is java.lang.Integer and V\r
+ * is defined as GeneratedType the array will contain two Types to store\r
+ * the information of generic parameters.)\r
+ *\r
+ * @return array of Types that are defined for Parameterized Type.\r
+ */\r
Type[] getActualTypeArguments();\r
\r
+ /**\r
+ * Returns the Raw Type definition of Parameterized Type.\r
+ *\r
+ * @return the Raw Type definition of Parameterized Type.\r
+ */\r
Type getRawType();\r
}\r
*/\r
package org.opendaylight.controller.sal.binding.model.api;\r
\r
+/**\r
+ * The Type interface defines the base type for all types defined in java.\r
+ * Each Type defined in java MUST contain name and package name,\r
+ * except of primitive types like int, byte etc. In case of mapping of\r
+ * primitive type the package name MUST be left as empty string.\r
+ *\r
+ */\r
public interface Type {\r
/**\r
* Returns name of the package that interface belongs to.\r
* @return name of the interface.\r
*/\r
public String getName();\r
+\r
+ /**\r
+ * Returns fully qualified name of Type.\r
+ * <br>\r
+ * The fully qualified name of Type MUST be returned in following format:\r
+ * <ul>\r
+ * <li>If does not contains package name: [type name] (e.g. int, byte,\r
+ * byte[],...)</li>\r
+ * <li>If Type contains package name: [package name].[type name]\r
+ * (e.g java.lang.Byte, org.opendaylight.controller.gen.GenType)</li>\r
+ * </ul>\r
+ *\r
+ * @return fully qualified name of Type.\r
+ */\r
+ public String getFullyQualifiedName();\r
}\r
--- /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.sal.binding.model.api;
+
+import java.util.List;
+
+public interface TypeMember {
+
+ /**
+ * Returns List of annotation definitions associated with generated type.
+ *
+ * @return List of annotation definitions associated with generated type.
+ */
+ public List<AnnotationType> getAnnotations();
+
+ /**
+ * Returns the name of method.
+ *
+ * @return the name of method.
+ */
+ public String getName();
+
+ /**
+ * Returns comment string associated with method.
+ *
+ * @return comment string associated with method.
+ */
+ public String getComment();
+
+ /**
+ * Returns the Type that declares method.
+ *
+ * @return the Type that declares method.
+ */
+ public Type getDefiningType();
+
+ /**
+ * Returns the access modifier of method.
+ *
+ * @return the access modifier of method.
+ */
+ public AccessModifier getAccessModifier();
+
+ /**
+ * Returns the returning Type that methods returns.
+ *
+ * @return the returning Type that methods returns.
+ */
+ public Type getReturnType();
+
+ /**
+ * Returns <code>true</code> if method is declared as final.
+ *
+ * @return <code>true</code> if method is declared as final.
+ */
+ public boolean isFinal();
+}
import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
import org.opendaylight.controller.sal.binding.model.api.Type;
+/**
+ * Annotation Type Builder Interface serves for creation and instantiation of
+ * immutable copy of Annotation Type. The Annotation Type Builder extends
+ * from {@link Type} interface. The Annotation Type contains set of methods
+ * which are capable to provide information about other Annotation Types and
+ * Annotation Parameters.
+ *
+ * @see AnnotationType
+ */
public interface AnnotationTypeBuilder extends Type {
-
+
+ /**
+ * The method creates new AnnotationTypeBuilder containing specified
+ * package name an annotation name.
+ * <br>
+ * Neither the package name or annotation name can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param packageName Package Name of Annotation Type
+ * @param name Name of Annotation Type
+ * @return <code>new</code> instance of Annotation Type Builder.
+ */
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-
+
+ /**
+ * Adds the parameter into List of parameters for Annotation Type.
+ * <br>
+ * If there is already stored parameter with the same name as the new
+ * parameter, the value of the old one will be simply overwritten by the
+ * newer parameter.
+ * <br>
+ * Neither the param name or value can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param paramName Parameter Name
+ * @param value Parameter Value
+ * @return <code>true</code> if the parameter has been successfully
+ * assigned for Annotation Type
+ */
public boolean addParameter(final String paramName, String value);
-
+
+ /**
+ * Adds the parameter with specified List of parameter values into List of
+ * parameters for Annotation Type.
+ * <br>
+ * If there is already stored parameter with the same name as the new
+ * parameter, the value of the old one will be simply overwritten by the
+ * newer parameter.
+ * <br>
+ * Neither the param name or value can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param paramName Parameter Name
+ * @param values List of Values bounded to Parameter Name
+ * @return <code>true</code> if the parameter has been successfully
+ * assigned for Annotation Type
+ */
public boolean addParameters(final String paramName, List<String> values);
-
+
+ /**
+ * Returns <code>new</code> <i>immutable</i> instance of Annotation Type
+ * with values assigned in current instance of Annotation Type Builder.
+ * <br>
+ * The return Annotation Type instance is immutable thus no additional
+ * modification to Annotation Type Builder will have an impact to
+ * instantiated Annotation Type.
+ * <br>
+ * For this purpose call this method after
+ * all additions are complete.
+ *
+ * @return <code>new</code> <i>immutable</i> instance of Annotation Type.
+ */
public AnnotationType toInstance();
}
import org.opendaylight.controller.sal.binding.model.api.Type;\r
\r
/**\r
-\r
*\r
*/\r
public interface ConstantBuilder {\r
import org.opendaylight.controller.sal.binding.model.api.Type;
/**
-
+ * Enum Builder is interface that contains methods to build and instantiate
+ * Enumeration definition.
*
+ * @see Enumeration
*/
public interface EnumBuilder extends Type {
-
+
+ /**
+ * The method creates new AnnotationTypeBuilder containing specified
+ * package name an annotation name.
+ * <br>
+ * Neither the package name or annotation name can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param packageName Package Name of Annotation Type
+ * @param name Name of Annotation Type
+ * @return <code>new</code> instance of Annotation Type Builder.
+ */
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-
+
+ /**
+ *
+ * @param name
+ * @param value
+ */
public void addValue(final String name, final Integer value);
+ /**
+ *
+ * @param definingType
+ * @return
+ */
public Enumeration toInstance(final Type definingType);
}
*/
package org.opendaylight.controller.sal.binding.model.api.type.builder;
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
import org.opendaylight.controller.sal.binding.model.api.Type;
/**
-
+ * Generated Property Builder is interface that contains methods to build and
+ * instantiate Generated Property definition.
*
+ * @see GeneratedProperty
*/
-public interface GeneratedPropertyBuilder {
-
- public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-
- public String getName();
-
- public boolean addReturnType(final Type returnType);
-
- public void accessorModifier(final AccessModifier modifier);
-
- public void addComment(final String comment);
-
- public void setFinal(final boolean isFinal);
-
+public interface GeneratedPropertyBuilder extends TypeMemberBuilder {
+
+ /**
+ * Sets isReadOnly flag for property. If property is marked as read only
+ * it is the same as set property in java as final.
+ *
+ * @param isReadOnly Read Only property flag.
+ */
public void setReadOnly(final boolean isReadOnly);
-
+
+ /**
+ * Returns <code>new</code> <i>immutable</i> instance of Generated
+ * Property.
+ * <br>
+ * The <code>definingType</code> param cannot be <code>null</code>. The
+ * every member in Java MUST be declared and defined inside the scope of
+ * <code>class</code> definition. In case that
+ * defining Type will be passed as <code>null</code> reference the method
+ * SHOULD thrown {@link IllegalArgumentException}.
+ *
+ * @param definingType Defining Type of Generated Property
+ * @return <code>new</code> <i>immutable</i> instance of Generated
+ * Property.
+ */
public GeneratedProperty toInstance(final Type definingType);
}
import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
/**
-
+ * Generated Transfer Object Builder is interface that contains methods to
+ * build and instantiate Generated Transfer Object definition.
+ *
+ * @see GeneratedTransferObject
*/
public interface GeneratedTOBuilder extends GeneratedTypeBuilder {
- public boolean addExtendsType(final GeneratedTransferObject genTransObj);
+ /**
+ * Add Generated Transfer Object from which will be extended current
+ * Generated Transfer Object.
+ * <br>
+ * By definition Java does not allow multiple
+ * inheritance, hence if there is already definition of Generated
+ * Transfer Object the extending object will be overwritten by lastly
+ * added Generated Transfer Object.
+ * <br>
+ * If Generated Transfer Object is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param genTransObj Generated Transfer Object
+ */
+ public void setExtendsType(final GeneratedTransferObject genTransObj);
+ /**
+ * Add new Generated Property definition for Generated Transfer Object
+ * Builder and returns Generated Property Builder for specifying Property.
+ * <br>
+ * Name of Property cannot be <code>null</code>,
+ * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+ *
+ * @param name Name of Property
+ * @return <code>new</code> instance of Generated Property Builder.
+ */
public GeneratedPropertyBuilder addProperty(final String name);
+ /**
+ * Add Property that will be part of <code>equals</code> definition.
+ * <br>
+ * If Generated Property Builder is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param property Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list
+ * of <code>equals</code> properties is successful.
+ */
public boolean addEqualsIdentity(final GeneratedPropertyBuilder property);
+ /**
+ * Add Property that will be part of <code>hashCode</code> definition.
+ * <br>
+ * If Generated Property Builder is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param property Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list
+ * of <code>hashCode</code> properties is successful.
+ */
public boolean addHashIdentity(final GeneratedPropertyBuilder property);
+ /**
+ * Add Property that will be part of <code>toString</code> definition.
+ * <br>
+ * If Generated Property Builder is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param property Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list
+ * of <code>toString</code> properties is successful.
+ */
public boolean addToStringProperty(final GeneratedPropertyBuilder property);
@Override
public GeneratedTransferObject toInstance();
-
- public GeneratedTransferObject toIdentityInstance();
-
}
*/
package org.opendaylight.controller.sal.binding.model.api.type.builder;
+import org.opendaylight.controller.sal.binding.model.api.Constant;
import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
import org.opendaylight.controller.sal.binding.model.api.Type;
/**
-
+ * Generated Type Builder interface is helper interface for building and
+ * defining the GeneratedType.
*
+ * @see GeneratedType
*/
public interface GeneratedTypeBuilder extends Type {
- public Type getParentType();
+ /**
+ * Adds new Enclosing Type into definition of Generated Type and returns
+ * <code>new</code> Instance of Generated Type Builder.
+ * <br>
+ * There is no need of specifying of Package Name because enclosing Type
+ * is already defined inside Generated Type with specific package name.
+ * <br>
+ * The name of enclosing Type cannot be same as Name of parent type and
+ * if there is already defined enclosing type with the same name,
+ * the new enclosing type will simply overwrite the older definition.
+ * <br>
+ * If the name of enclosing type is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param name Name of Enclosing Type
+ * @return <code>new</code> Instance of Generated Type Builder.
+ */
+ public GeneratedTypeBuilder addEnclosingType(final String name);
+
+ /**
+ * Adds new Enclosing Transfer Object into definition of Generated Type
+ * and returns <code>new</code> Instance of Generated TO Builder.
+ * <br>
+ * There is no need of specifying of Package Name because enclosing Type
+ * is already defined inside Generated Type with specific package name.
+ * <br>
+ * The name of enclosing Type cannot be same as Name of parent type and
+ * if there is already defined enclosing type with the same name,
+ * the new enclosing type will simply overwrite the older definition.
+ * <br>
+ * If the name of enclosing type is <code>null</code> the method SHOULD
+ * throw {@link IllegalArgumentException}
+ *
+ * @param name Name of Enclosing Type
+ * @return <code>new</code> Instance of Generated Type Builder.
+ */
+ public GeneratedTOBuilder addEnclosingTransferObject(final String name);
+ /**
+ * Adds String definition of comment into Method Signature definition.
+ * <br>
+ * The comment String MUST NOT contain anny comment specific chars (i.e.
+ * "/**" or "//") just plain String text description.
+ *
+ * @param comment Comment String.
+ */
public void addComment(final String comment);
-
+
+ /**
+ * The method creates new AnnotationTypeBuilder containing specified
+ * package name an annotation name.
+ * <br>
+ * Neither the package name or annotation name can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param packageName Package Name of Annotation Type
+ * @param name Name of Annotation Type
+ * @return <code>new</code> instance of Annotation Type Builder.
+ */
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-
+
+ /**
+ * Sets the <code>abstract</code> flag to define Generated Type as <i>abstract</i> type.
+ *
+ * @param isAbstract abstract flag
+ */
+ public void setAbstract(boolean isAbstract);
+
+ /**
+ * Add Type to implements.
+ *
+ * @param genType Type to implement
+ * @return <code>true</code> if the addition of type is successful.
+ */
public boolean addImplementsType(final Type genType);
-
- public ConstantBuilder addConstant(final Type type, final String name,
+
+ /**
+ * Adds Constant definition and returns <code>new</code> Constant instance.
+ * <br>
+ * By definition Constant MUST be defined by return Type,
+ * Name and assigned value. The name SHOULD be defined with cpaital
+ * letters. Neither of method parameters can be <code>null</code> and the
+ * method SHOULD throw {@link IllegalArgumentException} if the contract
+ * is broken.
+ *
+ * @param type Constant Type
+ * @param name Name of Constant
+ * @param value Assigned Value
+ * @return <code>new</code> Constant instance.
+ */
+ public Constant addConstant(final Type type, final String name,
final Object value);
+ /**
+ * Adds new Enumeration definition for Generated Type Builder and returns
+ * Enum Builder for specifying all Enum parameters.
+ * <br>
+ * If there is already Enumeration stored with the same name,
+ * the old enum will be simply overwritten byt new enum definition.
+ * <br>
+ * Name of Enumeration cannot be <code>null</code>,
+ * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+ *
+ * @param name Enumeration Name
+ * @return <code>new</code> instance of Enumeration Builder.
+ */
public EnumBuilder addEnumeration(final String name);
+ /**
+ * Add new Method Signature definition for Generated Type Builder and
+ * returns Method Signature Builder for specifying all Method parameters.
+ * <br>
+ * Name of Method cannot be <code>null</code>,
+ * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+ * <br>
+ * By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
+ * {@link MethodSignatureBuilder#setAbstract(true)}, {@link MethodSignatureBuilder#setFinal(false)} and
+ * {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
+ *
+ * @param name Name of Method
+ * @return <code>new</code> instance of Method Signature Builder.
+ */
public MethodSignatureBuilder addMethod(final String name);
+ /**
+ * Returns the <code>new</code> <i>immutable</i> instance of Generated
+ * Type.
+ *
+ * @return the <code>new</code> <i>immutable</i> instance of Generated
+ * Type.
+ */
public GeneratedType toInstance();
}
import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
import org.opendaylight.controller.sal.binding.model.api.Type;
-public interface MethodSignatureBuilder {
-
- public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-
- public void addReturnType(final Type returnType);
+/**
+ * Method Signature Builder serves solely for building Method Signature and
+ * returning the <code>new</code> instance of Method Signature.
+ * <br>
+ * By definition of {@link MethodSignature} the Method in java MUST contain
+ * Name, Return Type and Access Modifier. By default the Access Modifier can
+ * be set to public. The Method Signature builder does not contain method for
+ * addName due to enforce reason that MethodSignatureBuilder SHOULD be
+ * instantiated only once with defined method name.
+ * <br>
+ * The methods as {@link #addAnnotation(String, String)} and {@link #setComment(String)}
+ * can be used as optional because not all methods MUST contain annotation or
+ * comment definitions.
+ *
+ *
+ * @see MethodSignature
+ */
+public interface MethodSignatureBuilder extends TypeMemberBuilder {
- public void addParameter(final Type type, final String name);
+ /**
+ * Sets the flag for declaration of method as abstract or non abstract. If the flag <code>isAbstract == true</code>
+ * The instantiated Method Signature MUST have return value for {@link org.opendaylight.controller.sal.binding
+ * .model.api.MethodSignature#isAbstract()} also equals to <code>true</code>.
+ *
+ * @param isAbstract is abstract flag
+ */
+ public void setAbstract(boolean isAbstract);
- public void addComment(final String comment);
+ /**
+ * Adds Parameter into the List of method parameters. Neither the Name or
+ * Type of parameter can be <code>null</code>.
+ *
+ * <br>
+ * In case that any of parameters are defined as <code>null</code> the
+ * method SHOULD throw an {@link IllegalArgumentException}
+ *
+ * @param type Parameter Type
+ * @param name Parameter Name
+ */
+ public void addParameter(final Type type, final String name);
+ /**
+ * Returns <code>new</code> <i>immutable</i> instance of Method Signature.
+ * <br>
+ * The <code>definingType</code> param cannot be <code>null</code>. The
+ * every method in Java MUST be declared and defined inside the scope of
+ * <code>class</code> or <code>interface</code> definition. In case that
+ * defining Type will be passed as <code>null</code> reference the method
+ * SHOULD thrown {@link IllegalArgumentException}.
+ *
+ * @param definingType Defining Type of Method Signature
+ * @return <code>new</code> <i>immutable</i> instance of Method Signature.
+ */
public MethodSignature toInstance(final Type definingType);
}
--- /dev/null
+package org.opendaylight.controller.sal.binding.model.api.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+/**
+ *
+ */
+public interface TypeMemberBuilder {
+
+ /**
+ * The method creates new AnnotationTypeBuilder containing specified
+ * package name an annotation name.
+ * <br>
+ * Neither the package name or annotation name can contain
+ * <code>null</code> references. In case that
+ * any of parameters contains <code>null</code> the method SHOULD thrown
+ * {@link IllegalArgumentException}
+ *
+ * @param packageName Package Name of Annotation Type
+ * @param name Name of Annotation Type
+ * @return <code>new</code> instance of Annotation Type Builder.
+ */
+ public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
+
+ /**
+ * Returns the name of property.
+ *
+ * @return the name of property.
+ */
+ public String getName();
+
+ /**
+ * Adds return Type into Builder definition for Generated Property.
+ * <br>
+ * The return Type MUST NOT be <code>null</code>,
+ * otherwise the method SHOULD throw {@link IllegalArgumentException}
+ *
+ * @param returnType Return Type of property.
+ */
+ public void setReturnType(final Type returnType);
+
+ /**
+ * Sets the access modifier of property.
+ *
+ * @param modifier Access Modifier value.
+ */
+ public void setAccessModifier(final AccessModifier modifier);
+
+ /**
+ * Adds String definition of comment into Method Signature definition.
+ * <br>
+ * The comment String MUST NOT contain anny comment specific chars (i.e.
+ * "/**" or "//") just plain String text description.
+ *
+ * @param comment Comment String.
+ */
+ public void setComment(final String comment);
+
+ /**
+ * Sets the flag final for method signature. If this is set the method will be prohibited from overriding.
+ * <br>
+ * This setting is irrelevant for methods designated to be defined in interface definitions because interface
+ * can't have final method.
+ *
+ * @param isFinal Is Final
+ */
+ public void setFinal(final boolean isFinal);
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.sal.authorization.UserLevel;
-import org.opendaylight.controller.usermanager.ODLUserLevel;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
import org.springframework.security.core.GrantedAuthority;
public class AuthenticatedUserTest {
import org.opendaylight.controller.sal.utils.ObjectWriter;
import org.opendaylight.controller.sal.utils.Status;
import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
import org.opendaylight.controller.usermanager.AuthorizationConfig;
import org.opendaylight.controller.usermanager.IAAAProvider;
import org.opendaylight.controller.usermanager.ISessionManager;
import org.opendaylight.controller.usermanager.UserConfig;
import org.opendaylight.controller.usermanager.security.SessionManager;
import org.opendaylight.controller.usermanager.security.UserSecurityContextRepository;
-import org.opendaylight.controller.usermanager.internal.AuthenticatedUser;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.opendaylight.controller.sal.authorization.UserLevel;
import org.opendaylight.controller.sal.utils.ServiceHelper;
import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
import org.opendaylight.controller.usermanager.IAAAProvider;
import org.opendaylight.controller.usermanager.IUserManager;
import org.opendaylight.controller.usermanager.ServerConfig;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
-import org.opendaylight.controller.usermanager.IUserManager;
import org.opendaylight.controller.web.DaylightWebUtil;
import org.opendaylight.controller.web.IDaylightWeb;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting;
import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig;
+import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.authorization.UserLevel;
import org.opendaylight.controller.sal.core.Config;
import org.opendaylight.controller.sal.core.Name;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.core.Tier;
+import org.opendaylight.controller.sal.utils.GlobalConstants;
import org.opendaylight.controller.sal.utils.HexEncode;
import org.opendaylight.controller.sal.utils.ServiceHelper;
import org.opendaylight.controller.sal.utils.Status;
@RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET)
@ResponseBody
- public DevicesJsonBean getNodesLearnt(HttpServletRequest request, @RequestParam(required = false) String container) {
+ public DevicesJsonBean getNodesLearnt(HttpServletRequest request,
+ @RequestParam(required = false) String container) {
Gson gson = new Gson();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
List<Map<String, String>> nodeData = new ArrayList<Map<String, String>>();
- if (switchManager != null) {
+ if (switchManager != null && privilege != Privilege.NONE) {
for (Switch device : switchManager.getNetworkDevices()) {
HashMap<String, String> nodeDatum = new HashMap<String, String>();
Node node = device.getNode();
DevicesJsonBean result = new DevicesJsonBean();
result.setNodeData(nodeData);
+ result.setPrivilege(privilege);
List<String> columnNames = new ArrayList<String>();
columnNames.add("Node ID");
columnNames.add("Node Name");
@RequestParam("nodeId") String nodeId,
@RequestParam("tier") String tier,
@RequestParam("operationMode") String operationMode,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil
+ .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
@RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
@ResponseBody
- public DevicesJsonBean getStaticRoutes(HttpServletRequest request, @RequestParam(required = false) String container) {
+ public DevicesJsonBean getStaticRoutes(HttpServletRequest request,
+ @RequestParam(required = false) String container) {
Gson gson = new Gson();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
.getInstance(IForwardingStaticRouting.class, containerName,
this);
if (routeConfigs == null) {
return null;
}
- for (StaticRouteConfig conf : routeConfigs.values()) {
- Map<String, String> staticRoute = new HashMap<String, String>();
- staticRoute.put("name", conf.getName());
- staticRoute.put("staticRoute", conf.getStaticRoute());
- staticRoute.put("nextHopType", conf.getNextHopType());
- staticRoute.put("nextHop", conf.getNextHop());
- staticRoute.put("json", gson.toJson(conf));
- staticRoutes.add(staticRoute);
+ if (privilege != Privilege.NONE) {
+ for (StaticRouteConfig conf : routeConfigs.values()) {
+ Map<String, String> staticRoute = new HashMap<String, String>();
+ staticRoute.put("name", conf.getName());
+ staticRoute.put("staticRoute", conf.getStaticRoute());
+ staticRoute.put("nextHopType", conf.getNextHopType());
+ staticRoute.put("nextHop", conf.getNextHop());
+ staticRoute.put("json", gson.toJson(conf));
+ staticRoutes.add(staticRoute);
+ }
}
DevicesJsonBean result = new DevicesJsonBean();
+ result.setPrivilege(privilege);
result.setColumnNames(StaticRouteConfig.getGuiFieldsNames());
result.setNodeData(staticRoutes);
return result;
@RequestParam("routeName") String routeName,
@RequestParam("staticRoute") String staticRoute,
@RequestParam("nextHop") String nextHop,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil
+ .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean result = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
.getInstance(IForwardingStaticRouting.class, containerName,
@ResponseBody
public StatusJsonBean deleteStaticRoute(
@RequestParam("routesToDelete") String routesToDelete,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
.getInstance(IForwardingStaticRouting.class, containerName,
@RequestMapping(value = "/subnets", method = RequestMethod.GET)
@ResponseBody
- public DevicesJsonBean getSubnetGateways(HttpServletRequest request, @RequestParam(required = false) String container) {
+ public DevicesJsonBean getSubnetGateways(HttpServletRequest request,
+ @RequestParam(required = false) String container) {
Gson gson = new Gson();
List<Map<String, String>> subnets = new ArrayList<Map<String, String>>();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- ISwitchManager switchManager = (ISwitchManager) ServiceHelper
- .getInstance(ISwitchManager.class, containerName, this);
- if (switchManager != null) {
- for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
- Map<String, String> subnet = new HashMap<String, String>();
- subnet.put("name", conf.getName());
- subnet.put("subnet", conf.getSubnet());
- subnet.put("json", gson.toJson(conf));
- subnets.add(subnet);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(
+ userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+ .getInstance(ISwitchManager.class, containerName, this);
+ if (switchManager != null) {
+ for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
+ Map<String, String> subnet = new HashMap<String, String>();
+ subnet.put("name", conf.getName());
+ subnet.put("subnet", conf.getSubnet());
+ subnet.put("json", gson.toJson(conf));
+ subnets.add(subnet);
+ }
}
}
DevicesJsonBean result = new DevicesJsonBean();
+ result.setPrivilege(privilege);
result.setColumnNames(SubnetConfig.getGuiFieldsNames());
result.setNodeData(subnets);
return result;
public StatusJsonBean addSubnetGateways(
@RequestParam("gatewayName") String gatewayName,
@RequestParam("gatewayIPAddress") String gatewayIPAddress,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
@ResponseBody
public StatusJsonBean deleteSubnetGateways(
@RequestParam("gatewaysToDelete") String gatewaysToDelete,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
public StatusJsonBean addSubnetGatewayPort(
@RequestParam("portsName") String portsName,
@RequestParam("ports") String ports,
- @RequestParam("nodeId") String nodeId,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ @RequestParam("nodeId") String nodeId, HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
public StatusJsonBean deleteSubnetGatewayPort(
@RequestParam("gatewayName") String gatewayName,
@RequestParam("nodePort") String nodePort,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
try {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
@RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
@ResponseBody
- public DevicesJsonBean getSpanPorts(HttpServletRequest request, @RequestParam(required = false) String container) {
+ public DevicesJsonBean getSpanPorts(HttpServletRequest request,
+ @RequestParam(required = false) String container) {
Gson gson = new Gson();
- List<String> spanConfigs_json = new ArrayList<String>();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- ISwitchManager switchManager = (ISwitchManager) ServiceHelper
- .getInstance(ISwitchManager.class, containerName, this);
- if (switchManager != null) {
- for (SpanConfig conf : switchManager.getSpanConfigList()) {
- spanConfigs_json.add(gson.toJson(conf));
- }
- }
- ObjectMapper mapper = new ObjectMapper();
List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
- for (String config_json : spanConfigs_json) {
- try {
- @SuppressWarnings("unchecked")
- Map<String, String> config_data = mapper.readValue(config_json,
- HashMap.class);
- Map<String, String> config = new HashMap<String, String>();
- for (String name : config_data.keySet()) {
- config.put(name, config_data.get(name));
- // Add switch name value (non-configuration field)
- config.put("nodeName",
- getNodeDesc(config_data.get("nodeId"), containerName));
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(
+ userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ List<String> spanConfigs_json = new ArrayList<String>();
+ ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+ .getInstance(ISwitchManager.class, containerName, this);
+ if (switchManager != null) {
+ for (SpanConfig conf : switchManager.getSpanConfigList()) {
+ spanConfigs_json.add(gson.toJson(conf));
+ }
+ }
+ ObjectMapper mapper = new ObjectMapper();
+
+ for (String config_json : spanConfigs_json) {
+ try {
+ @SuppressWarnings("unchecked")
+ Map<String, String> config_data = mapper.readValue(config_json,
+ HashMap.class);
+ Map<String, String> config = new HashMap<String, String>();
+ for (String name : config_data.keySet()) {
+ config.put(name, config_data.get(name));
+ // Add switch name value (non-configuration field)
+ config.put("nodeName",
+ getNodeDesc(config_data.get("nodeId"), containerName));
+ }
+ config.put("json", config_json);
+ spanConfigs.add(config);
+ } catch (Exception e) {
+ // TODO: Handle the exception.
}
- config.put("json", config_json);
- spanConfigs.add(config);
- } catch (Exception e) {
- // TODO: Handle the exception.
}
}
+
DevicesJsonBean result = new DevicesJsonBean();
+ result.setPrivilege(privilege);
result.setColumnNames(SpanConfig.getGuiFieldsNames());
result.setNodeData(spanConfigs);
return result;
@RequestMapping(value = "/nodeports")
@ResponseBody
- public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ public Map<String, Object> getNodePorts(HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+ return null;
+ }
+
+
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
if (switchManager == null) {
port = new HashMap<Short, String>(); // new port
Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
- if (nodeConnectorSet != null)
+ if (nodeConnectorSet != null) {
for (NodeConnector nodeConnector : nodeConnectorSet) {
String nodeConnectorName = ((Name) switchManager
.getNodeConnectorProp(nodeConnector,
port.put((Short) nodeConnector.getID(), nodeConnectorName
+ "(" + nodeConnector.getID() + ")");
}
+ }
nodes.put(node.getNode().toString(), port);
}
@ResponseBody
public StatusJsonBean addSpanPort(
@RequestParam("jsonData") String jsonData,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
try {
Gson gson = new Gson();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
@ResponseBody
public StatusJsonBean deleteSpanPorts(
@RequestParam("spanPortsToDelete") String spanPortsToDelete,
- HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ HttpServletRequest request,
+ @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT
+ .toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return unauthorizedMessage();
}
StatusJsonBean resultBean = new StatusJsonBean();
try {
Gson gson = new Gson();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
String[] spans = spanPortsToDelete.split("###");
: description;
}
- /**
- * Is the operation permitted for the given level
- *
- * @param level
- */
- private boolean authorize(UserLevel level, HttpServletRequest request) {
- IUserManager userManager = (IUserManager) ServiceHelper
- .getGlobalInstance(IUserManager.class, this);
- if (userManager == null) {
- return false;
- }
-
- String username = request.getUserPrincipal().getName();
- UserLevel userLevel = userManager.getUserLevel(username);
- if (userLevel.toNumber() <= level.toNumber()) {
- return true;
- }
- return false;
- }
-
private StatusJsonBean unauthorizedMessage() {
StatusJsonBean message = new StatusJsonBean();
message.setStatus(false);
import java.util.List;
import java.util.Map;
+import org.opendaylight.controller.sal.authorization.Privilege;
+
public class DevicesJsonBean {
private List<String> columnNames;
private List<Map<String, String>> nodeData;
+ private Privilege privilege;
public List<String> getColumnNames() {
return columnNames;
public void setNodeData(List<Map<String, String>> nodeData) {
this.nodeData = nodeData;
}
+
+ public void setPrivilege(Privilege privilege) {
+ this.privilege = privilege;
+ }
+
+ public Privilege getPrivilege() {
+ return privilege;
+ }
}
modal : {
initialize: {
updateNode: function(evt) {
- var nodeId = decodeURIComponent(evt.target.id);
- var h3 = "Update Node Information";
- var footer = one.f.switchmanager.nodesLearnt.modal.footer.updateNode();
- var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.modal, h3, "", footer);
-
- // bind save button
- $('#' + one.f.switchmanager.nodesLearnt.id.modal.save, $modal).click(function() {
- one.f.switchmanager.nodesLearnt.modal.save($modal);
- });
- // inject body (nodePorts)
one.f.switchmanager.nodesLearnt.ajax.main(one.f.switchmanager.rootUrl + "/tiers", function(tiers) {
- var $body = one.f.switchmanager.nodesLearnt.modal.body.updateNode(nodeId, evt.target.switchDetails, tiers);
+
+ var nodeId = decodeURIComponent(evt.target.id);
+ var h3;
+ var footer = [];
+ var $body = one.f.switchmanager.nodesLearnt.modal.body.updateNode(nodeId, evt.target.switchDetails, tiers);
+ if ( (one.main.registry == undefined || one.main.registry.container == 'default') && evt.target.privilege == 'WRITE'){
+ h3 = "Update Node Information";
+ footer = one.f.switchmanager.nodesLearnt.modal.footer.updateNode();
+ } else { //disable node edit
+ $body.find('*').attr('disabled', 'disabled');
+ h3 = 'Node Information';
+ }
+
+ var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.modal, h3, "", footer);
+ // bind save button
+ $('#' + one.f.switchmanager.nodesLearnt.id.modal.save, $modal).click(function() {
+ one.f.switchmanager.nodesLearnt.modal.save($modal);
+ });
+
+ // inject body (nodePorts)
one.lib.modal.inject.body($modal, $body);
$modal.modal();
});
$select.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.operationMode);
$select.val(switchDetails["mode"]);
$fieldset.append($label).append($select);
-
$form.append($fieldset);
return $form;
},
footer: {
updateNode: function() {
var footer = [];
- if(one.role < 2) {
- var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.nodesLearnt.id.modal.save, "btn-success", "");
- var $saveButton = one.lib.dashlet.button.button(saveButton);
- footer.push($saveButton);
- }
+ var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.nodesLearnt.id.modal.save, "btn-success", "");
+ var $saveButton = one.lib.dashlet.button.button(saveButton);
+ footer.push($saveButton);
+
return footer;
},
popout: function() {
var tr = {};
var entry = [];
var nodenameentry = value["nodeName"] ? value["nodeName"] : "Click to update";
+
// TODO: Move anchor tag creation to one.lib.form.
- var aTag = document.createElement("a");
- aTag.setAttribute("id", encodeURIComponent(value["nodeId"]));
- aTag.switchDetails = value;
- aTag.addEventListener("click", one.f.switchmanager.nodesLearnt.modal.initialize.updateNode);
- aTag.addEventListener("mouseover", function(evt) {
- evt.target.style.cursor = "pointer";
- }, false);
+ var aTag;
+ aTag = document.createElement("a");
+ aTag.privilege = data.privilege;
+ aTag.addEventListener("click", one.f.switchmanager.nodesLearnt.modal.initialize.updateNode);
+ aTag.addEventListener("mouseover", function(evt) {
+ evt.target.style.cursor = "pointer";
+ }, false);
+ aTag.setAttribute("id", encodeURIComponent(value["nodeId"]));
+ aTag.switchDetails = value;
aTag.innerHTML = nodenameentry;
entry.push(aTag);
entry.push(value["nodeId"]);
one.lib.dashlet.empty($dashlet);
$dashlet.append(one.lib.dashlet.header(one.f.dashlet.subnetGatewayConfig.name));
// Add gateway IP Address button
- if(one.role < 2) {
- var button = one.lib.dashlet.button.single("Add Gateway IP Address",
- one.f.switchmanager.subnetGatewayConfig.id.dashlet.addIPAddress, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
- var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.gateway();
- $modal.modal();
- });
- $dashlet.append($button);
-
-
- // Delete gateway ip address button
- var button = one.lib.dashlet.button.single("Delete Gateway IP Address(es)",
- one.f.switchmanager.subnetGatewayConfig.id.dashlet.removeIPAddress, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
- var requestData = {};
- var gatewaysToDelete = [];
- var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
- checkedCheckBoxes.each(function(index, value) {
- gatewaysToDelete.push(checkedCheckBoxes[index].id);
- });
- if(gatewaysToDelete.length > 0) {
- requestData["gatewaysToDelete"] = gatewaysToDelete.toString();
- var url = one.f.switchmanager.rootUrl + "/subnetGateway/delete";
- one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) {
- if(response.status == true) {
- // refresh dashlet by passing dashlet div as param
- one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet"));
- } else {
- alert(response.message);
- }
- });
- }
- });
- $dashlet.append($button);
-
- // Add Ports button
- var button = one.lib.dashlet.button.single("Add Ports",
- one.f.switchmanager.subnetGatewayConfig.id.dashlet.addPorts, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
- var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.ports();
- $modal.modal();
- });
- $dashlet.append($button);
- }
var url = one.f.switchmanager.rootUrl + "/subnets";
one.f.switchmanager.subnetGatewayConfig.ajax.main(url, {}, function(content) {
+
+ if (content.privilege === 'WRITE') {
+ var button = one.lib.dashlet.button.single("Add Gateway IP Address",
+ one.f.switchmanager.subnetGatewayConfig.id.dashlet.addIPAddress, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+ var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.gateway();
+ $modal.modal();
+ });
+ $dashlet.append($button);
+
+ // Delete gateway ip address button
+ var button = one.lib.dashlet.button.single("Delete Gateway IP Address(es)",
+ one.f.switchmanager.subnetGatewayConfig.id.dashlet.removeIPAddress, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+ var requestData = {};
+ var gatewaysToDelete = [];
+ var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+ checkedCheckBoxes.each(function(index, value) {
+ gatewaysToDelete.push(checkedCheckBoxes[index].id);
+ });
+ if (gatewaysToDelete.length > 0) {
+ requestData["gatewaysToDelete"] = gatewaysToDelete.toString();
+ var url = one.f.switchmanager.rootUrl + "/subnetGateway/delete";
+ one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) {
+ if (response.status == true) {
+ // refresh dashlet by passing dashlet div as param
+ one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet"));
+ } else {
+ alert(response.message);
+ }
+ });
+ }
+ });
+ $dashlet.append($button);
+
+ // Add Ports button
+ var button = one.lib.dashlet.button.single("Add Ports",
+ one.f.switchmanager.subnetGatewayConfig.id.dashlet.addPorts, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+ var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.ports();
+ $modal.modal();
+ });
+ $dashlet.append($button);
+ }
+
var body = one.f.switchmanager.subnetGatewayConfig.data.devices(content);
// first column contains checkbox. no need for header
content.columnNames.splice(0,0," ");
},
footer : function() {
var footer = [];
- if(one.role < 2) {
- var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.subnetGatewayConfig.id.modal.save, "btn-success", "");
- var $saveButton = one.lib.dashlet.button.button(saveButton);
- footer.push($saveButton);
- }
+ var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.subnetGatewayConfig.id.modal.save, "btn-success", "");
+ var $saveButton = one.lib.dashlet.button.button(saveButton);
+ footer.push($saveButton);
return footer;
}
},
dashlet: function($dashlet) {
one.lib.dashlet.empty($dashlet);
- if(one.role < 2) {
- // Add static route button
- var button = one.lib.dashlet.button.single("Add Static Route",
- one.f.switchmanager.staticRouteConfig.id.dashlet.add, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
- var $modal = one.f.switchmanager.staticRouteConfig.modal.initialize();
- $modal.modal();
- });
- $dashlet.append(one.lib.dashlet.header(one.f.dashlet.staticRouteConfig.name));
- $dashlet.append($button);
-
- // Delete static route button
- var button = one.lib.dashlet.button.single("Delete Static Route(s)",
- one.f.switchmanager.staticRouteConfig.id.dashlet.remove, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
- var requestData = {};
- var routesToDelete = [];
- var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
- checkedCheckBoxes.each(function(index, value) {
- routesToDelete.push(checkedCheckBoxes[index].id);
- });
- if(routesToDelete.length > 0) {
- requestData["routesToDelete"] = routesToDelete.toString();
- var url = one.f.switchmanager.rootUrl + "/staticRoute/delete";
- one.f.switchmanager.staticRouteConfig.ajax.main(url, requestData, function(response) {
- if(response.status == true) {
- // refresh dashlet by passing dashlet div as param
- one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet"));
- } else {
- alert(response.message);
- }
- });
- }
- });
- $dashlet.append($button);
- }
-
+
var url = one.f.switchmanager.rootUrl + "/staticRoutes";
one.f.switchmanager.staticRouteConfig.ajax.main(url, {}, function(content) {
+
+ if (content.privilege === 'WRITE') {
+ // Add static route button
+ var button = one.lib.dashlet.button.single("Add Static Route", one.f.switchmanager.staticRouteConfig.id.dashlet.add, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+ var $modal = one.f.switchmanager.staticRouteConfig.modal.initialize();
+ $modal.modal();
+ });
+ $dashlet.append(one.lib.dashlet.header(one.f.dashlet.staticRouteConfig.name));
+ $dashlet.append($button);
+
+ // Delete static route button
+ var button = one.lib.dashlet.button.single("Delete Static Route(s)", one.f.switchmanager.staticRouteConfig.id.dashlet.remove, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+ var requestData = {};
+ var routesToDelete = [];
+ var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+ checkedCheckBoxes.each(function(index, value) {
+ routesToDelete.push(checkedCheckBoxes[index].id);
+ });
+ if (routesToDelete.length > 0) {
+ requestData["routesToDelete"] = routesToDelete.toString();
+ var url = one.f.switchmanager.rootUrl + "/staticRoute/delete";
+ one.f.switchmanager.staticRouteConfig.ajax.main(url, requestData, function(response) {
+ if (response.status == true) {
+ // refresh dashlet by passing dashlet div as param
+ one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet"));
+ } else {
+ alert(response.message);
+ }
+ });
+ }
+ });
+ $dashlet.append($button);
+ }
+
var body = one.f.switchmanager.staticRouteConfig.data.staticRouteConfig(content);
// first column contains checkbox. no need for header
content.columnNames.splice(0,0," ");
},
footer : function() {
var footer = [];
- if (one.role < 2) {
- var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.staticRouteConfig.id.modal.save, "btn-success", "");
- var $saveButton = one.lib.dashlet.button.button(saveButton);
- footer.push($saveButton);
- }
+ var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.staticRouteConfig.id.modal.save, "btn-success", "");
+ var $saveButton = one.lib.dashlet.button.button(saveButton);
+ footer.push($saveButton);
return footer;
}
},
},
dashlet: function($dashlet) {
one.lib.dashlet.empty($dashlet);
- if(one.role < 2) {
-
- // Add span port button
- var button = one.lib.dashlet.button.single("Add Span Port", one.f.switchmanager.spanPortConfig.id.dashlet.add, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
-
- $button.click(function() {
- var $modal = one.f.switchmanager.spanPortConfig.modal.initialize();
- $modal.modal();
- });
- $dashlet.append(one.lib.dashlet.header(one.f.dashlet.spanPortConfig.name));
- $dashlet.append($button);
-
- // Delete span port button
- var button = one.lib.dashlet.button.single("Delete SPAN Port(s)",
- one.f.switchmanager.spanPortConfig.id.dashlet.remove, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
- $button.click(function() {
-
- var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
- if(checkedCheckBoxes.length > 0) {
- var spanPortsToDelete = "";
- checkedCheckBoxes.each(function(index, value) {
- spanPortsToDelete += checkedCheckBoxes[index].spanPort + "###";
- });
-
- var requestData = {};
- requestData["spanPortsToDelete"] = spanPortsToDelete;
- var url = one.f.switchmanager.rootUrl + "/spanPorts/delete";
- one.f.switchmanager.spanPortConfig.ajax.main(url, requestData, function(response) {
- if(response.status == true) {
- // refresh dashlet by passing dashlet div as param
- one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet"));
- } else {
- alert(response.message);
- }
- });
- }
- });
- $dashlet.append($button);
- }
//populate table in dashlet
var url = one.f.switchmanager.rootUrl + "/spanPorts";
one.f.switchmanager.spanPortConfig.ajax.main(url, {}, function(content) {
+
+ if (content.privilege === 'WRITE') {
+
+ // Add span port button
+ var button = one.lib.dashlet.button.single("Add Span Port", one.f.switchmanager.spanPortConfig.id.dashlet.add, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+
+ $button.click(function() {
+ var $modal = one.f.switchmanager.spanPortConfig.modal.initialize();
+ $modal.modal();
+ });
+ $dashlet.append(one.lib.dashlet.header(one.f.dashlet.spanPortConfig.name));
+ $dashlet.append($button);
+
+ // Delete span port button
+ var button = one.lib.dashlet.button.single("Delete SPAN Port(s)", one.f.switchmanager.spanPortConfig.id.dashlet.remove, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+ $button.click(function() {
+
+ var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+ if (checkedCheckBoxes.length > 0) {
+ var spanPortsToDelete = "";
+ checkedCheckBoxes.each(function(index, value) {
+ spanPortsToDelete += checkedCheckBoxes[index].spanPort + "###";
+ });
+
+ var requestData = {};
+ requestData["spanPortsToDelete"] = spanPortsToDelete;
+ var url = one.f.switchmanager.rootUrl + "/spanPorts/delete";
+ one.f.switchmanager.spanPortConfig.ajax.main(url, requestData, function(response) {
+ if (response.status == true) {
+ // refresh dashlet by passing dashlet div as param
+ one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet"));
+ } else {
+ alert(response.message);
+ }
+ });
+ }
+ });
+ $dashlet.append($button);
+ }
+
var body = one.f.switchmanager.spanPortConfig.data.devices(content);
// first column contains the checkbox. no header required.
content.columnNames.splice(0,0," ");
},
footer : function() {
var footer = [];
- if (one.role < 2) {
- var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.spanPortConfig.id.modal.save, "btn-success", "");
- var $saveButton = one.lib.dashlet.button.button(saveButton);
- footer.push($saveButton);
- }
+ var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.spanPortConfig.id.modal.save, "btn-success", "");
+ var $saveButton = one.lib.dashlet.button.button(saveButton);
+ footer.push($saveButton);
return footer;
}
},
import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
+import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.authorization.UserLevel;
import org.opendaylight.controller.sal.core.Name;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.GlobalConstants;
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.ISwitchManager;
import org.opendaylight.controller.switchmanager.Switch;
import org.opendaylight.controller.switchmanager.SwitchConfig;
-import org.opendaylight.controller.usermanager.IUserManager;
import org.opendaylight.controller.web.DaylightWebUtil;
import org.opendaylight.controller.web.IDaylightWeb;
import org.springframework.stereotype.Controller;
@RequestMapping(value = "/main")
@ResponseBody
- public Set<Map<String, Object>> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ public Map<String, Object> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+ if (privilege == Privilege.NONE) {
+ return null;
+ }
// fetch frm
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
// get static flow list
List<FlowConfig> staticFlowList = frm.getStaticFlows();
- Set<Map<String, Object>> output = new HashSet<Map<String, Object>>();
+ Set<Map<String, Object>> flowSet = new HashSet<Map<String, Object>>();
for (FlowConfig flowConfig : staticFlowList) {
Map<String, Object> entry = new HashMap<String, Object>();
entry.put("flow", flowConfig);
entry.put("node", (description.isEmpty() || description
.equalsIgnoreCase("none")) ? node.toString() : description);
entry.put("nodeId", node.toString());
- output.add(entry);
+ flowSet.add(entry);
}
+ Map <String, Object> output = new HashMap<String, Object>(2);
+ output.put("flows", flowSet);
+ output.put("privilege", privilege);
return output;
}
@RequestMapping(value = "/node-ports")
@ResponseBody
public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+ return null;
+ }
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
@RequestMapping(value = "/node-flows")
@ResponseBody
public Map<String, Object> getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+ return null;
+ }
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
@RequestParam(required = false) String body,
@RequestParam(required = true) String nodeId,
HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return "Operation not authorized";
}
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
.getInstance(IForwardingRulesManager.class, containerName, this);
if (frm == null) {
.getDescription();
}
- @RequestMapping(value = "/flow/{nodeId}/{name}", method = RequestMethod.POST)
+ @RequestMapping(value = "/flow/{nodeId}/{name:.*}", method = RequestMethod.POST)
@ResponseBody
public String removeFlow(@PathVariable("nodeId") String nodeId,
@PathVariable("name") String name,
@RequestParam(required = true) String action,
HttpServletRequest request, @RequestParam(required = false) String container) {
- if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Authorization check
+ String userName = request.getUserPrincipal().getName();
+ if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
return "Operation not authorized";
}
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
.getInstance(IForwardingRulesManager.class, containerName, this);
if (frm == null) {
return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result
.getDescription();
}
-
- /**
- * Returns whether the current user's level is same or above the required
- * authorization level.
- *
- * @param requiredLevel
- * the authorization level required
- */
- private boolean isUserAuthorized(UserLevel requiredLevel,
- HttpServletRequest request) {
- IUserManager userManager = (IUserManager) ServiceHelper
- .getGlobalInstance(IUserManager.class, this);
- if (userManager == null) {
- return false;
- }
-
- String username = request.getUserPrincipal().getName();
- UserLevel userLevel = userManager.getUserLevel(username);
- return (userLevel.ordinal() <= requiredLevel.ordinal());
- }
-
}
-/*
- * 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,
+/*
+ * 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
*/
dashlet : function($dashlet) {
var $h4 = one.lib.dashlet.header("Nodes");
$dashlet.append($h4);
-
+
// load body
one.f.nodes.ajax.dashlet(function($table) {
// total nodes count
dashlet : function(body, callback) {
var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed'];
var $table = one.lib.dashlet.table.table(attributes);
-
+
var headers = ['Node', 'Flows'];
var $thead = one.lib.dashlet.table.header(headers);
$table.append($thead);
-
+
var $tbody = one.lib.dashlet.table.body(body);
$table.append($tbody);
-
+
return $table;
}
}
dashlet : function($dashlet, details) {
var $h4 = one.lib.dashlet.header("Flow Details");
$dashlet.append($h4);
-
+
// details
if (details == undefined) {
var $none = $(document.createElement('div'));
var $p = $(document.createElement('p'));
$p.text('Please select a flow');
$p.addClass('text-center').addClass('text-info');
-
+
$dashlet.append($none)
.append($p);
}
},
registry : {},
dashlet : function($dashlet, callback) {
- var $h4 = one.lib.dashlet.header("Flow Entries");
-
- if (one.role < 2) {
- var button = one.lib.dashlet.button.single("Add Flow Entry", one.f.flows.id.dashlet.add, "btn-primary", "btn-mini");
- var $button = one.lib.dashlet.button.button(button);
-
- $button.click(function() {
- var $modal = one.f.flows.modal.initialize();
- $modal.modal();
- });
- }
-
- $dashlet.append($h4);
- if (one.role < 2) $dashlet.append($button);
-
+
// load body
one.f.flows.ajax.dashlet(function($table) {
+
+ var $h4 = one.lib.dashlet.header("Flow Entries");
+
+ $dashlet.append($h4);
+ if (one.f.flows.registry.privilege === 'WRITE') {
+ var button = one.lib.dashlet.button.single("Add Flow Entry", one.f.flows.id.dashlet.add, "btn-primary", "btn-mini");
+ var $button = one.lib.dashlet.button.button(button);
+
+ $button.click(function() {
+ var $modal = one.f.flows.modal.initialize();
+ $modal.modal();
+ });
+ $dashlet.append($button);
+
+ }
+
+ // table bindings
+ $table.find('tbody').find('tr').click(function() {
+ var id = $($(this).find('td')[0]).text();
+ var node = $(this).data('id');
+ one.f.flows.detail(id, node);
+ });
+
// total flows
var flowCount = $table.find('tbody').find('tr').size();
// prompt output
$p = $(document.createElement('p'));
$p.append(out);
$dashlet.append($p);
- // table bindings
- $table.find('tbody').find('tr').click(function() {
- var id = $($(this).find('td')[0]).text();
- var node = $(this).data('id');
- one.f.flows.detail(id, node);
- });
- // add to dashlet
+ // add table to dashlet
$dashlet.append($table);
// details callback
if(callback != undefined) callback();
$detailDashlet.empty();
var $h4 = one.lib.dashlet.header("Flow Overview");
$detailDashlet.append($h4);
-
+
// details
var flows = one.f.flows.registry.flows;
var flow;
flow = value;
}
});
- if (one.role < 2) {
+ if (one.f.flows.registry.privilege === 'WRITE') {
// remove button
var button = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.dashlet.remove, "btn-danger", "btn-mini");
var $button = one.lib.dashlet.button.button(button);
}
});
});
+
+ $detailDashlet.append($button).append($toggle);
}
// append details
var body = one.f.detail.data.dashlet(flow);
var $body = one.f.detail.body.dashlet(body);
- if (one.role < 2) $detailDashlet.append($button).append($toggle);
$detailDashlet.append($body);
var body = one.f.detail.data.description(flow);
var $body = one.f.detail.body.description(body);
},
footer : function() {
var footer = [];
-
+
var removeButton = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.modal.dialog.remove, "btn-danger", "");
var $removeButton = one.lib.dashlet.button.button(removeButton);
footer.push($removeButton);
-
+
var closeButton = one.lib.dashlet.button.single("Cancel", one.f.flows.id.modal.dialog.close, "", "");
var $closeButton = one.lib.dashlet.button.button(closeButton);
footer.push($closeButton);
-
+
return footer;
},
body : function(id) {
var h3 = "Add Flow Entry";
var footer = one.f.flows.modal.footer();
var $modal = one.lib.modal.spawn(one.f.flows.id.modal.modal, h3, "", footer);
-
+
// bind close button
$('#'+one.f.flows.id.modal.close, $modal).click(function() {
$modal.modal('hide');
});
-
+
// bind add flow button
$('#'+one.f.flows.id.modal.add, $modal).click(function() {
one.f.flows.modal.add($modal, 'false');
$('#'+one.f.flows.id.modal.install, $modal).click(function() {
one.f.flows.modal.add($modal, 'true');
});
-
+
// inject body (nodePorts)
one.f.flows.modal.ajax.nodes(function(nodes, nodeports) {
var $body = one.f.flows.modal.body(nodes, nodeports);
one.lib.modal.inject.body($modal, $body);
});
-
+
return $modal;
},
add : function($modal, install) {
var result = {};
-
+
result['name'] = $('#'+one.f.flows.id.modal.form.name, $modal).val();
result['ingressPort'] = $('#'+one.f.flows.id.modal.form.port, $modal).val();
result['priority'] = $('#'+one.f.flows.id.modal.form.priority, $modal).val();
result['installInHw'] = install;
var nodeId = $('#'+one.f.flows.id.modal.form.nodes, $modal).val();
-
+
$.each(result, function(key, value) {
if (value == "") delete result[key];
});
-
+
var action = [];
var $table = $('#'+one.f.flows.id.modal.action.table, $modal);
$($table.find('tbody').find('tr')).each(function(index, value) {
}
});
result['actions'] = action;
-
+
// frontend validation
if (result['name'] == undefined) {
alert('Need flow name');
alert('Please specify an action');
return;
}
-
+
// package for ajax call
var resource = {};
resource['body'] = JSON.stringify(result);
resource['action'] = 'add';
resource['nodeId'] = nodeId;
-
+
one.f.flows.modal.ajax.saveflow(resource, function(data) {
if (data == "Success") {
$modal.modal('hide');
var nodes = one.f.flows.modal.data.nodes(data);
var nodeports = data;
one.f.flows.registry['nodeports'] = nodeports;
-
+
successCallback(nodes, nodeports);
});
},
one.lib.form.select.prepend($select, { '' : 'Please Select a Node' });
$select.val($select.find("option:first").val());
$select.attr('id', one.f.flows.id.modal.form.nodes);
-
+
// bind onchange
$select.change(function() {
// retrieve port value
one.f.flows.modal.action.parse(action.attr('value'));
$select[0].selectedIndex = 0;
});
-
+
$fieldset.append($select).append($table);
-
+
// return
$form.append($fieldset);
return $form;
var addButton = one.lib.dashlet.button.single("Add Action", one.f.flows.id.modal.action.add, "btn-primary", "");
var $addButton = one.lib.dashlet.button.button(addButton);
footer.push($addButton);
-
+
var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.action.close, "", "");
var $closeButton = one.lib.dashlet.button.button(closeButton);
footer.push($closeButton);
-
+
return footer;
}
},
var installButton = one.lib.dashlet.button.single("Install Flow", one.f.flows.id.modal.install, "btn-success", "");
var $installButton = one.lib.dashlet.button.button(installButton);
footer.push($installButton);
-
+
var addButton = one.lib.dashlet.button.single("Save Flow", one.f.flows.id.modal.add, "btn-primary", "");
var $addButton = one.lib.dashlet.button.button(addButton);
footer.push($addButton);
-
+
var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.close, "", "");
var $closeButton = one.lib.dashlet.button.button(closeButton);
footer.push($closeButton);
-
+
return footer;
}
},
ajax : {
dashlet : function(callback) {
$.getJSON(one.f.address.root+one.f.address.flows.main, function(data) {
- one.f.flows.registry['flows'] = data;
- var body = one.f.flows.data.dashlet(data);
+ one.f.flows.registry['flows'] = data.flows;
+ one.f.flows.registry['privilege'] = data.privilege;
+ var body = one.f.flows.data.dashlet(data.flows);
var $body = one.f.flows.body.dashlet(body, callback);
callback($body);
});
tr['type'] = ['warning'];
tr['entry'] = entry;
tr['id'] = value['nodeId'];
-
+
body.push(tr);
});
return body;
dashlet : function(body, callback) {
var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed', 'table-cursor'];
var $table = one.lib.dashlet.table.table(attributes);
-
+
var headers = ['Flow Name', 'Node'];
var $thead = one.lib.dashlet.table.header(headers);
$table.append($thead);
-
+
var $tbody = one.lib.dashlet.table.body(body);
$table.append($tbody);
-
+
return $table;
}
}
package org.opendaylight.controller.web;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-
import org.opendaylight.controller.containermanager.IContainerAuthorization;
-import org.opendaylight.controller.sal.authorization.Resource;
+import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.utils.GlobalConstants;
import org.opendaylight.controller.sal.utils.ServiceHelper;
+import org.opendaylight.controller.usermanager.IUserManager;
public class DaylightWebUtil {
- private static String defaultName = GlobalConstants.DEFAULT.toString();
/**
- * Returns the container that this user is authorized to access. If the user is not authorized to the requested
- * container, then this method will return the default container.
+ * Returns the access privilege the user has on the specified container
*
- * @param request - HttpServletRequest object to retrieve username
- * @param container - requested container
- * @param bundle - respective bundle
- * @return container name if cleared, else it will always be 'default'
+ * @param userName
+ * The user name
+ * @param container
+ * The container name. If null, the default container will be assumed
+ * @param bundle
+ * The bundle originating the request
+ * @return The access privilege the user is granted on the container
*/
- public static String getAuthorizedContainer(HttpServletRequest request, String container, Object bundle) {
- if (container == null) {
- return defaultName;
+ public static Privilege getContainerPrivilege(String userName,
+ String container, Object bundle) {
+ // Derive the target resource
+ String resource = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Retrieve the Container Authorization service
+ IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper
+ .getGlobalInstance(IContainerAuthorization.class, bundle);
+ if (auth != null) {
+ return auth.getResourcePrivilege(userName, resource);
}
- String username = request.getUserPrincipal().getName();
- IContainerAuthorization containerAuthorization = (IContainerAuthorization)
- ServiceHelper.getGlobalInstance(IContainerAuthorization.class, bundle);
- if (containerAuthorization != null) {
- Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
- for(Resource resource : resources) {
- String name = (String) resource.getResource();
- if(container.equals(name)) {
- return name;
+ /*
+ * Container Authorization service not available. We can only derive the
+ * access privilege to the default container based on user level
+ */
+ if (resource.equals(GlobalConstants.DEFAULT.toString())) {
+ IUserManager userManager = (IUserManager) ServiceHelper
+ .getGlobalInstance(IUserManager.class, bundle);
+ if (userManager != null) {
+ switch (userManager.getUserLevel(userName)) {
+ case NETWORKADMIN:
+ return Privilege.WRITE;
+ case NETWORKOPERATOR:
+ return Privilege.READ;
+ default:
+ return Privilege.NONE;
}
}
}
- return defaultName;
+
+ return Privilege.NONE;
}
}
\ No newline at end of file
import javax.servlet.http.HttpServletRequest;
import org.opendaylight.controller.configuration.IConfigurationAware;
-import org.opendaylight.controller.containermanager.IContainerAuthorization;
-import org.opendaylight.controller.sal.authorization.Resource;
-import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.core.Bandwidth;
import org.opendaylight.controller.sal.core.Edge;
import org.opendaylight.controller.sal.core.Host;
+import org.opendaylight.controller.sal.core.Name;
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.switchmanager.Switch;
import org.opendaylight.controller.switchmanager.SwitchConfig;
import org.opendaylight.controller.topologymanager.ITopologyManager;
-import org.opendaylight.controller.usermanager.IUserManager;
import org.opendaylight.controller.web.DaylightWebUtil;
-import org.opendaylight.controller.web.IDaylightWeb;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping(value = "/visual.json", method = RequestMethod.GET)
@ResponseBody
public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container, HttpServletRequest request) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+ if (privilege == Privilege.NONE) {
+ return null;
+ }
ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
.getInstance(ITopologyManager.class, containerName, this);
break;
}
}
- EdgeBean edge = new EdgeBean(link, bandwidth);
+ NodeConnector headNodeConnector = link.getHeadNodeConnector();
+ NodeConnector tailNodeConnector = link.getTailNodeConnector();
+
+ String headDescription = this.getNodeConnectorDescription(headNodeConnector, switchManager);
+ String tailDescription = this.getNodeConnectorDescription(tailNodeConnector, switchManager);
+ String headPortDescription = this.getNodeConnectorPortDescription(headNodeConnector, switchManager);
+ String tailPortDescription = this.getNodeConnectorPortDescription(tailNodeConnector, switchManager);
+ EdgeBean edge = new EdgeBean(link, bandwidth, headDescription, tailDescription, headPortDescription, tailPortDescription);
adjacencies.add(edge.out());
}
}
protected NodeBean createNodeBean(String description, Node node) {
+ String name = this.getDescription(description, node);
+ return new NodeBean(node.toString(), name, NodeType.NODE);
+ }
+
+ private String getDescription(String description, Node node) {
String name = (description == null ||
- description.trim().isEmpty() ||
- description.equalsIgnoreCase("none"))?
- node.toString() : description;
- return new NodeBean(node.toString(), name, NodeType.NODE);
+ description.trim().isEmpty() ||
+ description.equalsIgnoreCase("none"))?
+ node.toString() : description;
+ return name;
+ }
+
+ private String getNodeConnectorDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
+ Node node = nodeConnector.getNode();
+ String description = switchManager.getNodeDescription(node);
+ String name = this.getDescription(description, node);
+ return name;
+ }
+
+ private String getNodeConnectorPortDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
+ Name ncName = (Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName);
+ String nodeConnectorName = nodeConnector.getNodeConnectorIDString();
+ if (ncName != null) {
+ nodeConnectorName = ncName.getValue();
+ }
+ return nodeConnectorName;
}
@SuppressWarnings("unchecked")
public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
@RequestParam(required = true) String y, @RequestParam(required = false) String container,
HttpServletRequest request) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
- return new HashMap<String, Object>(); // silently disregard new node position
- }
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
- String containerName = getAuthorizedContainer(request, container);
+ if (privilege != Privilege.WRITE) {
+ return new HashMap<String, Object>(); // silently disregard new node position
+ }
String id = new String(nodeId);
data = new HashMap<String, String>();
}
- public EdgeBean(Edge link, Bandwidth bandwidth) {
- this();
- this.source = link.getHeadNodeConnector();
- this.destination = link.getTailNodeConnector();
-
- // data
- data.put("$bandwidth", bandwidth.toString());
- data.put("$color", bandwidthColor(bandwidth));
- data.put("$nodeToPort", destination.getID().toString());
- data.put("$nodeFromPort", source.getID().toString());
- data.put("$descFrom", source.getNode().toString());
- data.put("$descTo", destination.getNode().toString());
- data.put("$nodeFromPortName", source.toString());
- data.put("$nodeToPortName", destination.toString());
+ /**
+ * EdgeBean object that includes complete node description
+ *
+ * @param link
+ * @param bandwidth
+ * @param headDescription
+ * @param tailDescription
+ */
+ public EdgeBean(Edge link, Bandwidth bandwidth, String headDescription,
+ String tailDescription, String headPortDescription, String tailPortDescription) {
+ this();
+ this.source = link.getHeadNodeConnector();
+ this.destination = link.getTailNodeConnector();
+
+ // data
+ data.put("$bandwidth", bandwidth.toString());
+ data.put("$color", bandwidthColor(bandwidth));
+ data.put("$nodeToPort", destination.getID().toString());
+ data.put("$nodeFromPort", source.getID().toString());
+ data.put("$descFrom", headDescription);
+ data.put("$descTo", tailDescription);
+ data.put("$nodeFromPortName", source.toString());
+ data.put("$nodeToPortName", destination.toString());
+ data.put("$nodeFromPortDescription", headPortDescription);
+ data.put("$nodeToPortDescription", tailPortDescription);
}
public EdgeBean(NodeConnector connector, Long hostId) {
- this();
- this.source = null;
- this.destination = connector;
- this.hostId = hostId;
-
- data.put("$bandwidth", "N/A");
- data.put("$color", bandwidthColor(new Bandwidth(0)));
- data.put("$nodeToPort", connector.getNodeConnectorIDString());
- data.put("$nodeFromPort", connector.getNodeConnectorIDString());
- data.put("$descTo", "");
- data.put("$descFrom", "");
- data.put("$nodeToPortName", "");
- data.put("$nodeFromPortName", "");
+ this();
+ this.source = null;
+ this.destination = connector;
+ this.hostId = hostId;
+
+ data.put("$bandwidth", "N/A");
+ data.put("$color", bandwidthColor(new Bandwidth(0)));
+ data.put("$nodeToPort", connector.getNodeConnectorIDString());
+ data.put("$nodeFromPort", connector.getNodeConnectorIDString());
+ data.put("$descTo", "");
+ data.put("$descFrom", "");
+ data.put("$nodeToPortName", "");
+ data.put("$nodeFromPortName", "");
}
public Map<String, Object> out() {
public static final String HOST = "host";
}
- private boolean authorize(UserLevel level, HttpServletRequest request) {
- IUserManager userManager = (IUserManager) ServiceHelper
- .getGlobalInstance(IUserManager.class, this);
- if (userManager == null) {
- return false;
- }
-
- String username = request.getUserPrincipal().getName();
- UserLevel userLevel = userManager.getUserLevel(username);
- if (userLevel.toNumber() <= level.toNumber()) {
- return true;
- }
- return false;
- }
-
- private String getAuthorizedContainer(HttpServletRequest request, String container) {
- String username = request.getUserPrincipal().getName();
- IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
- getGlobalInstance(IContainerAuthorization.class, this);
- if (containerAuthorization != null) {
- Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
- if (authorizeContainer(container, resources)) {
- return container;
- }
- }
-
- return GlobalConstants.DEFAULT.toString();
- }
-
- private boolean authorizeContainer(String container, Set<Resource> resources) {
- for(Resource resource : resources) {
- String containerName = (String) resource.getResource();
- if (containerName.equals(container)) {
- return true;
- }
- }
-
- return false;
- }
-
@SuppressWarnings("unchecked")
private void loadConfiguration() {
ObjectReader objReader = new ObjectReader();
metaCache = (Map<String, Map<String, Map<String, Object>>>) objReader.read(this, topologyWebFileName);
- if (metaCache == null) metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
+ if (metaCache == null) {
+ metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
+ }
}
@Override
import java.util.Date;
import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.opendaylight.controller.sal.action.Action;
import org.opendaylight.controller.sal.action.Output;
import org.opendaylight.controller.sal.action.SetVlanId;
+import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.authorization.UserLevel;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
@RequestMapping("/")
public class Troubleshoot implements IDaylightWeb {
private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER;
+ private static final List<String> flowStatsColumnNames = Arrays.asList("Node", "In Port",
+ "DL Src", "DL Dst", "DL Type", "DL Vlan", "NW Src", "NW Dst",
+ "NW Proto", "TP Src", "TP Dst", "Actions", "Bytes", "Packets",
+ "Time (s)", "Timeout (s)", "Out Port(s)", "Out Vlan",
+ "Priority");
+ private static final List<String> portStatsColumnNames = Arrays.asList("Node Connector",
+ "Rx Pkts", "Tx Pkts", "Rx Bytes", "Tx Bytes", "Rx Drops",
+ "Tx Drops", "Rx Errs", "Tx Errs", "Rx Frame Errs",
+ "Rx OverRun Errs", "Rx CRC Errs", "Collisions");
+ private static final List<String> nodesColumnNames = Arrays.asList("Node", "Node ID", "Statistics");
+ private static final List<String> nodeStatsColumnNames = Arrays.asList("Node", "Node ID", "Statistics");
private final String WEB_NAME = "Troubleshoot";
private final String WEB_ID = "troubleshoot";
private final short WEB_ORDER = 4;
+
public Troubleshoot() {
ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null);
}
@RequestMapping(value = "/existingNodes", method = RequestMethod.GET)
@ResponseBody
public TroubleshootingJsonBean getExistingNodes(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- ISwitchManager switchManager = (ISwitchManager) ServiceHelper
- .getInstance(ISwitchManager.class, containerName, this);
- List<HashMap<String, String>> lines = new ArrayList<HashMap<String, String>>();
- Set<Node> nodeSet = null;
- if (switchManager != null) {
- nodeSet = switchManager.getNodes();
- }
- if (nodeSet != null) {
- for (Node node : nodeSet) {
- HashMap<String, String> device = new HashMap<String, String>();
- device.put("nodeName", switchManager.getNodeDescription(node));
- device.put("nodeId", node.toString());
- lines.add(device);
+ List<Map<String, String>> lines = new ArrayList<Map<String, String>>();
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+ .getInstance(ISwitchManager.class, containerName, this);
+ Set<Node> nodeSet = (switchManager != null) ? switchManager.getNodes() : null;
+ if (nodeSet != null) {
+ for (Node node : nodeSet) {
+ Map<String, String> device = new HashMap<String, String>();
+ device.put("nodeName", switchManager.getNodeDescription(node));
+ device.put("nodeId", node.toString());
+ lines.add(device);
+ }
}
}
- TroubleshootingJsonBean result = new TroubleshootingJsonBean();
- List<String> guiFieldNames = new ArrayList<String>();
- guiFieldNames.add("Node");
- guiFieldNames.add("Node ID");
- guiFieldNames.add("Statistics");
-
- result.setColumnNames(guiFieldNames);
+ TroubleshootingJsonBean result = new TroubleshootingJsonBean();
+ result.setColumnNames(nodesColumnNames);
result.setNodeData(lines);
return result;
}
@RequestMapping(value = "/uptime", method = RequestMethod.GET)
@ResponseBody
public TroubleshootingJsonBean getUptime(HttpServletRequest request, @RequestParam(required = false) String container) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- ISwitchManager switchManager = (ISwitchManager) ServiceHelper
- .getInstance(ISwitchManager.class, containerName, this);
- List<HashMap<String, String>> lines = new ArrayList<HashMap<String, String>>();
- Set<Node> nodeSet = null;
- if (switchManager != null) {
- nodeSet = switchManager.getNodes();
- }
- if (nodeSet != null) {
- for (Node node : nodeSet) {
- HashMap<String, String> device = new HashMap<String, String>();
- device.put("nodeName", switchManager.getNodeDescription(node));
- device.put("nodeId", node.toString());
- TimeStamp timeStamp = (TimeStamp) switchManager.getNodeProp(
- node, TimeStamp.TimeStampPropName);
- Long time = (timeStamp == null) ? 0 : timeStamp.getValue();
- String date = (time == 0) ? "" : (new Date(time)).toString();
- device.put("connectedSince", date);
- lines.add(device);
+ List<Map<String, String>> lines = new ArrayList<Map<String, String>>();
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+ .getInstance(ISwitchManager.class, containerName, this);
+ Set<Node> nodeSet = (switchManager != null) ? switchManager.getNodes() : null;
+ if (nodeSet != null) {
+ for (Node node : nodeSet) {
+ Map<String, String> device = new HashMap<String, String>();
+ device.put("nodeName", switchManager.getNodeDescription(node));
+ device.put("nodeId", node.toString());
+ TimeStamp timeStamp = (TimeStamp) switchManager.getNodeProp(
+ node, TimeStamp.TimeStampPropName);
+ Long time = (timeStamp == null) ? 0 : timeStamp.getValue();
+ String date = (time == 0) ? "" : (new Date(time)).toString();
+ device.put("connectedSince", date);
+ lines.add(device);
+ }
}
}
- TroubleshootingJsonBean result = new TroubleshootingJsonBean();
- List<String> guiFieldNames = new ArrayList<String>();
- guiFieldNames.add("Node");
- guiFieldNames.add("Node ID");
- guiFieldNames.add("Connected");
-
- result.setColumnNames(guiFieldNames);
+ TroubleshootingJsonBean result = new TroubleshootingJsonBean();
+ result.setColumnNames(nodeStatsColumnNames);
result.setNodeData(lines);
return result;
}
public TroubleshootingJsonBean getFlowStats(
@RequestParam("nodeId") String nodeId,
HttpServletRequest request, @RequestParam(required = false) String container) {
- Node node = Node.fromString(nodeId);
- List<HashMap<String, String>> cells = new ArrayList<HashMap<String, String>>();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
- .getInstance(IStatisticsManager.class, containerName, this);
-
- List<FlowOnNode> statistics = statisticsManager.getFlows(node);
- for (FlowOnNode stats : statistics) {
- cells.add(this.convertFlowStatistics(node, stats, containerName));
+ List<Map<String, String>> cells = new ArrayList<Map<String, String>>();
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
+ .getInstance(IStatisticsManager.class, containerName, this);
+ if (statisticsManager != null) {
+ Node node = Node.fromString(nodeId);
+ List<FlowOnNode> statistics = statisticsManager.getFlows(node);
+ for (FlowOnNode stats : statistics) {
+ cells.add(this.convertFlowStatistics(node, stats, containerName));
+ }
+ }
}
- List<String> columnNames = new ArrayList<String>();
- columnNames.addAll(Arrays.asList(new String[] { "Node", "In Port",
- "DL Src", "DL Dst", "DL Type", "DL Vlan", "NW Src", "NW Dst",
- "NW Proto", "TP Src", "TP Dst", "Actions", "Bytes", "Packets",
- "Time (s)", "Timeout (s)", "Out Port(s)", "Out Vlan",
- "Priority" }));
+
TroubleshootingJsonBean result = new TroubleshootingJsonBean();
- result.setColumnNames(columnNames);
+ result.setColumnNames(flowStatsColumnNames);
result.setNodeData(cells);
return result;
}
public TroubleshootingJsonBean getPortStats(
@RequestParam("nodeId") String nodeId,
HttpServletRequest request, @RequestParam(required = false) String container) {
- Node node = Node.fromString(nodeId);
- List<HashMap<String, String>> cells = new ArrayList<HashMap<String, String>>();
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
- IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
- .getInstance(IStatisticsManager.class, containerName, this);
- List<NodeConnectorStatistics> statistics = statisticsManager
- .getNodeConnectorStatistics(node);
- for (NodeConnectorStatistics stats : statistics) {
- cells.add(this.convertPortsStatistics(stats));
+ List<Map<String, String>> cells = new ArrayList<Map<String, String>>();
+ String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+ // Derive the privilege this user has on the current container
+ String userName = request.getUserPrincipal().getName();
+ Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+ if (privilege != Privilege.NONE) {
+ IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
+ .getInstance(IStatisticsManager.class, containerName, this);
+ if (statisticsManager != null) {
+ Node node = Node.fromString(nodeId);
+ List<NodeConnectorStatistics> statistics = statisticsManager
+ .getNodeConnectorStatistics(node);
+ for (NodeConnectorStatistics stats : statistics) {
+ cells.add(this.convertPortsStatistics(stats));
+ }
+ }
}
+
TroubleshootingJsonBean result = new TroubleshootingJsonBean();
- List<String> columnNames = new ArrayList<String>();
- columnNames.addAll(Arrays.asList(new String[] { "Node Connector",
- "Rx Pkts", "Tx Pkts", "Rx Bytes", "Tx Bytes", "Rx Drops",
- "Tx Drops", "Rx Errs", "Tx Errs", "Rx Frame Errs",
- "Rx OverRun Errs", "Rx CRC Errs", "Collisions" }));
- result.setColumnNames(columnNames);
+ result.setColumnNames(portStatsColumnNames);
result.setNodeData(cells);
return result;
}
- private HashMap<String, String> convertPortsStatistics(
+ private Map<String, String> convertPortsStatistics(
NodeConnectorStatistics ncStats) {
- HashMap<String, String> row = new HashMap<String, String>();
+ Map<String, String> row = new HashMap<String, String>();
row.put("nodeConnector",
String.valueOf(ncStats.getNodeConnector().toString()));
return row;
}
- private HashMap<String, String> convertFlowStatistics(Node node,
+ private Map<String, String> convertFlowStatistics(Node node,
FlowOnNode flowOnNode,
String containerName) {
- HashMap<String, String> row = new HashMap<String, String>();
+ Map<String, String> row = new HashMap<String, String>();
Flow flow = flowOnNode.getFlow();
Match match = flow.getMatch();
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
package org.opendaylight.controller.troubleshoot.web;
-import java.util.HashMap;
import java.util.List;
+import java.util.Map;
public class TroubleshootingJsonBean {
private List<String> columnNames;
- private List<HashMap<String, String>> nodeData;
+ private List<Map<String, String>> nodeData;
public List<String> getColumnNames() {
return columnNames;
this.columnNames = columnNames;
}
- public List<HashMap<String, String>> getNodeData() {
+ public List<Map<String, String>> getNodeData() {
return nodeData;
}
- public void setNodeData(List<HashMap<String, String>> nodeData) {
+ public void setNodeData(List<Map<String, String>> nodeData) {
this.nodeData = nodeData;
}
}