http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/plugins/network-elements/nuage-vsp/test/com/cloud/network/resource/NuageVspResourceTest.java
----------------------------------------------------------------------
diff --git 
a/plugins/network-elements/nuage-vsp/test/com/cloud/network/resource/NuageVspResourceTest.java
 
b/plugins/network-elements/nuage-vsp/test/com/cloud/network/resource/NuageVspResourceTest.java
index 0983ab6..e497ec4 100644
--- 
a/plugins/network-elements/nuage-vsp/test/com/cloud/network/resource/NuageVspResourceTest.java
+++ 
b/plugins/network-elements/nuage-vsp/test/com/cloud/network/resource/NuageVspResourceTest.java
@@ -28,9 +28,12 @@ import javax.naming.ConfigurationException;
 import net.nuage.vsp.acs.client.api.NuageVspApiClient;
 import net.nuage.vsp.acs.client.api.NuageVspElementClient;
 import net.nuage.vsp.acs.client.api.NuageVspGuruClient;
+import net.nuage.vsp.acs.client.api.NuageVspManagerClient;
+import net.nuage.vsp.acs.client.api.NuageVspPluginClientLoader;
 import net.nuage.vsp.acs.client.api.model.VspAclRule;
 import net.nuage.vsp.acs.client.api.model.VspDhcpDomainOption;
 import net.nuage.vsp.acs.client.api.model.VspDhcpVMOption;
+import net.nuage.vsp.acs.client.api.model.VspHost;
 import net.nuage.vsp.acs.client.api.model.VspNetwork;
 import net.nuage.vsp.acs.client.api.model.VspNic;
 import net.nuage.vsp.acs.client.api.model.VspStaticNat;
@@ -38,7 +41,8 @@ import net.nuage.vsp.acs.client.api.model.VspVm;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -56,45 +60,36 @@ import 
com.cloud.agent.api.guru.ReserveVmInterfaceVspCommand;
 import com.cloud.agent.api.guru.TrashNetworkVspCommand;
 import com.cloud.host.Host;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 public class NuageVspResourceTest extends NuageTest {
     private NuageVspResource _resource;
-    private NuageVspApiClient _mockNuageVspApiClient = 
mock(NuageVspApiClient.class);
-    private NuageVspElementClient _mockNuageVspElementClient = 
mock(NuageVspElementClient.class);
-    private NuageVspGuruClient _mockNuageVspGuruClient = 
mock(NuageVspGuruClient.class);
-    private NuageVspResource.Configuration _resourceConfiguration;
+    @Mock private NuageVspApiClient _mockNuageVspApiClient;
+    @Mock private NuageVspElementClient _mockNuageVspElementClient;
+    @Mock private NuageVspGuruClient _mockNuageVspGuruClient;
+    @Mock private NuageVspManagerClient _mockNuageVspManagerClient;
+    @Mock private NuageVspPluginClientLoader _mockNuageVspPluginClientLoader;
+    private NuageVspResourceConfiguration _resourceConfiguration;
     private Map<String, Object> _hostDetails;
 
-    org.mockito.stubbing.Answer<Object> genericAnswer = new 
org.mockito.stubbing.Answer<Object>() {
-        public Object answer(InvocationOnMock invocation) {
-            return null;
-        }
-    };
-
     @Before
     public void setUp() throws Exception {
         super.setUp();
 
-        _resource = new NuageVspResource() {
-
-            @Override
-            protected void loadNuageClient() {
-                _isNuageVspClientLoaded = true;
-                _nuageVspApiClient = _mockNuageVspApiClient;
-                _nuageVspElementClient = _mockNuageVspElementClient;
-                _nuageVspGuruClient = _mockNuageVspGuruClient;
-            }
-
-            protected void isNuageVspApiLoaded() throws ConfigurationException 
{
-            }
+        MockitoAnnotations.initMocks(this);
 
-            protected void isNuageVspGuruLoaded() throws 
ConfigurationException {
-            }
+        
when(_mockNuageVspPluginClientLoader.getNuageVspApiClient()).thenReturn(_mockNuageVspApiClient);
+        
when(_mockNuageVspPluginClientLoader.getNuageVspElementClient()).thenReturn(_mockNuageVspElementClient);
+        
when(_mockNuageVspPluginClientLoader.getNuageVspGuruClient()).thenReturn(_mockNuageVspGuruClient);
+        
when(_mockNuageVspPluginClientLoader.getNuageVspManagerClient()).thenReturn(_mockNuageVspManagerClient);
 
-            protected void isNuageVspElementLoaded() throws 
ConfigurationException {
+        _resource = new NuageVspResource() {
+            @Override protected NuageVspPluginClientLoader 
getClientLoader(VspHost vspHost) {
+                return _mockNuageVspPluginClientLoader;
             }
 
             protected void login() throws ConfigurationException {
@@ -102,8 +97,7 @@ public class NuageVspResourceTest extends NuageTest {
 
         };
 
-        _resourceConfiguration = new NuageVspResource.Configuration()
-                .name("nuagevsptestdevice")
+        _resourceConfiguration = new NuageVspResourceConfiguration()
                 .guid("aaaaa-bbbbb-ccccc")
                 .zoneId("blublub")
                 .hostName("nuagevsd")
@@ -124,21 +118,21 @@ public class NuageVspResourceTest extends NuageTest {
 
     @Test
     public void resourceConfigure() throws Exception {
-        _resource.configure("NuageVspResource", _hostDetails);
+        _resource.configure("Nuage VSD - nuagevsd", _hostDetails);
 
-        assertTrue("nuagevsptestdevice".equals(_resource.getName()));
-        assertTrue(_resource.getType() == Host.Type.L2Networking);
+        assertEquals("Nuage VSD - nuagevsd", _resource.getName());
+        assertEquals(Host.Type.L2Networking, _resource.getType());
     }
 
     @Test
     public void testInitialization() throws Exception {
-        _resource.configure("NuageVspResource", _hostDetails);
+        _resource.configure("Nuage VSD - nuagevsd", _hostDetails);
 
         StartupCommand[] sc = _resource.initialize();
-        assertTrue(sc.length == 1);
-        assertTrue("aaaaa-bbbbb-ccccc".equals(sc[0].getGuid()));
-        assertTrue("nuagevsptestdevice".equals(sc[0].getName()));
-        assertTrue("blublub".equals(sc[0].getDataCenter()));
+        assertEquals(1, sc.length);
+        assertEquals("aaaaa-bbbbb-ccccc", sc[0].getGuid());
+        assertEquals("Nuage VSD - nuagevsd", sc[0].getName());
+        assertEquals("blublub", sc[0].getDataCenter());
     }
 
     @Test
@@ -146,9 +140,9 @@ public class NuageVspResourceTest extends NuageTest {
         _resource.configure("NuageVspResource", _hostDetails);
 
         PingCommand ping = _resource.getCurrentStatus(42);
-        assertTrue(ping != null);
-        assertTrue(ping.getHostId() == 42);
-        assertTrue(ping.getHostType() == Host.Type.L2Networking);
+        assertNotNull(ping);
+        assertEquals(42, ping.getHostId());
+        assertEquals(Host.Type.L2Networking, ping.getHostType());
     }
 
     @Test
@@ -158,9 +152,9 @@ public class NuageVspResourceTest extends NuageTest {
         VspNetwork vspNetwork = buildVspNetwork();
         VspDhcpDomainOption vspDhcpOptions = buildspDhcpDomainOption();
         ImplementNetworkVspCommand cmd = new 
ImplementNetworkVspCommand(vspNetwork, vspDhcpOptions);
-        
doAnswer(genericAnswer).when(_mockNuageVspGuruClient).implement(vspNetwork, 
vspDhcpOptions);
         com.cloud.agent.api.Answer implNtwkAns = _resource.executeRequest(cmd);
         assertTrue(implNtwkAns.getResult());
+        verify(_mockNuageVspGuruClient).implement(vspNetwork, vspDhcpOptions);
     }
 
     @Test
@@ -173,7 +167,6 @@ public class NuageVspResourceTest extends NuageTest {
         VspStaticNat vspStaticNat = buildVspStaticNat();
         VspDhcpVMOption vspDhcpOption = buildspDhcpVMOption();
         ReserveVmInterfaceVspCommand cmd = new 
ReserveVmInterfaceVspCommand(vspNetwork, vspVm, vspNic, vspStaticNat, 
vspDhcpOption);
-        
doAnswer(genericAnswer).when(_mockNuageVspGuruClient).reserve(vspNetwork, 
vspVm, vspNic, vspStaticNat, vspDhcpOption);
         Answer rsrvVmInfAns = _resource.executeRequest(cmd);
         assertTrue(rsrvVmInfAns.getResult());
     }
@@ -186,7 +179,6 @@ public class NuageVspResourceTest extends NuageTest {
         VspVm vspVm = buildVspVm();
         VspNic vspNic = buildVspNic();
         DeallocateVmVspCommand cmd = new DeallocateVmVspCommand(vspNetwork, 
vspVm, vspNic);
-        
doAnswer(genericAnswer).when(_mockNuageVspGuruClient).deallocate(vspNetwork, 
vspVm, vspNic);
         Answer dellocateVmAns = _resource.executeRequest(cmd);
         assertTrue(dellocateVmAns.getResult());
     }
@@ -197,7 +189,6 @@ public class NuageVspResourceTest extends NuageTest {
 
         VspNetwork vspNetwork = buildVspNetwork();
         TrashNetworkVspCommand cmd = new TrashNetworkVspCommand(vspNetwork);
-        
doAnswer(genericAnswer).when(_mockNuageVspGuruClient).trash(vspNetwork);
         Answer trashNtwkAns = _resource.executeRequest(cmd);
         assertTrue(trashNtwkAns.getResult());
     }
@@ -209,7 +200,6 @@ public class NuageVspResourceTest extends NuageTest {
         VspNetwork vspNetwork = buildVspNetwork();
         List<VspStaticNat> vspStaticNatDetails = 
Lists.newArrayList(buildVspStaticNat());
         ApplyStaticNatVspCommand cmd = new 
ApplyStaticNatVspCommand(vspNetwork, vspStaticNatDetails);
-        
doAnswer(genericAnswer).when(_mockNuageVspElementClient).applyStaticNats(vspNetwork,
 vspStaticNatDetails);
         Answer applyNatAns = _resource.executeRequest(cmd);
         assertTrue(applyNatAns.getResult());
     }
@@ -221,7 +211,6 @@ public class NuageVspResourceTest extends NuageTest {
         VspNetwork vspNetwork = buildVspNetwork();
         List<VspAclRule> vspAclRules = Lists.newArrayList(buildVspAclRule());
         ApplyAclRuleVspCommand cmd = new 
ApplyAclRuleVspCommand(VspAclRule.ACLType.NetworkACL, vspNetwork, vspAclRules, 
false);
-        
doAnswer(genericAnswer).when(_mockNuageVspElementClient).applyAclRules(VspAclRule.ACLType.NetworkACL,
 vspNetwork, vspAclRules, false);
         Answer applyAclAns = _resource.executeRequest(cmd);
         assertTrue(applyAclAns.getResult());
     }
@@ -231,7 +220,6 @@ public class NuageVspResourceTest extends NuageTest {
         _resource.configure("NuageVspResource", _hostDetails);
 
         ShutDownVpcVspCommand cmd = new ShutDownVpcVspCommand("domainUuid", 
"vpcUuid", "domainTemplateName", Lists.<String>newArrayList());
-        
doAnswer(genericAnswer).when(_mockNuageVspElementClient).shutdownVpc("domainUuid",
 "vpcUuid", "domainTemplateName", Lists.<String>newArrayList());
         Answer shutVpcAns = _resource.executeRequest(cmd);
         assertTrue(shutVpcAns.getResult());
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/plugins/network-elements/nuage-vsp/test/com/cloud/util/NuageVspEntityBuilderTest.java
----------------------------------------------------------------------
diff --git 
a/plugins/network-elements/nuage-vsp/test/com/cloud/util/NuageVspEntityBuilderTest.java
 
b/plugins/network-elements/nuage-vsp/test/com/cloud/util/NuageVspEntityBuilderTest.java
index 26e36b4..a3f8752 100644
--- 
a/plugins/network-elements/nuage-vsp/test/com/cloud/util/NuageVspEntityBuilderTest.java
+++ 
b/plugins/network-elements/nuage-vsp/test/com/cloud/util/NuageVspEntityBuilderTest.java
@@ -19,6 +19,19 @@
 
 package com.cloud.util;
 
+import net.nuage.vsp.acs.client.api.model.Protocol;
+import net.nuage.vsp.acs.client.api.model.VspAclRule;
+import net.nuage.vsp.acs.client.api.model.VspDomain;
+import net.nuage.vsp.acs.client.api.model.VspNetwork;
+import net.nuage.vsp.acs.client.api.model.VspNic;
+import net.nuage.vsp.acs.client.api.model.VspStaticNat;
+import net.nuage.vsp.acs.client.api.model.VspVm;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
 import com.cloud.NuageTest;
 import com.cloud.dc.VlanDetailsVO;
 import com.cloud.dc.VlanVO;
@@ -29,6 +42,7 @@ import com.cloud.domain.dao.DomainDao;
 import com.cloud.network.Network;
 import com.cloud.network.dao.IPAddressDao;
 import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.NetworkDetailsDao;
 import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.rules.FirewallRule;
@@ -44,18 +58,6 @@ import com.cloud.utils.net.Ip;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
 import com.cloud.vm.VirtualMachine;
-import com.google.common.collect.Lists;
-import net.nuage.vsp.acs.client.api.model.VspAclRule;
-import net.nuage.vsp.acs.client.api.model.VspDomain;
-import net.nuage.vsp.acs.client.api.model.VspNetwork;
-import net.nuage.vsp.acs.client.api.model.VspNic;
-import net.nuage.vsp.acs.client.api.model.VspStaticNat;
-import net.nuage.vsp.acs.client.api.model.VspVm;
-import net.nuage.vsp.acs.client.common.model.Pair;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.List;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
@@ -78,6 +80,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
     private VpcDao _vpcDao = mock(VpcDao.class);
     private DomainDao _domainDao = mock(DomainDao.class);
     private AccountDao _accountDao = mock(AccountDao.class);
+    private NetworkDao _networkDao = mock(NetworkDao.class);
     private NetworkOfferingDao _networkOfferingDao = 
mock(NetworkOfferingDao.class);
     private NetworkOfferingServiceMapDao _networkOfferingServiceMapDao = 
mock(NetworkOfferingServiceMapDao.class);
     private VlanDao _vlanDao = mock(VlanDao.class);
@@ -114,6 +117,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
         _nuageVspEntityBuilder._vpcDao = _vpcDao;
         _nuageVspEntityBuilder._domainDao = _domainDao;
         _nuageVspEntityBuilder._accountDao = _accountDao;
+        _nuageVspEntityBuilder._networkDao = _networkDao;
         _nuageVspEntityBuilder._networkOfferingDao = _networkOfferingDao;
         _nuageVspEntityBuilder._networkOfferingServiceMapDao = 
_networkOfferingServiceMapDao;
         _nuageVspEntityBuilder._vlanDao = _vlanDao;
@@ -154,29 +158,29 @@ public class NuageVspEntityBuilderTest extends NuageTest {
 
     @Test
     public void testBuildVspNetwork() {
-        VspNetwork vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedL2Network, true);
-        validateVspNetwork(vspNetwork, true, false, false, false, 
"IsolatedDomainTemplate", true);
+        VspNetwork vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedL2Network);
+        validateVspNetwork(vspNetwork, true, false, false, false, 
"IsolatedDomainTemplate");
 
-        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedL2Network, 
false);
-        validateVspNetwork(vspNetwork, true, false, false, false, 
"IsolatedDomainTemplate", false);
+        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedL2Network);
+        validateVspNetwork(vspNetwork, true, false, false, false, 
"IsolatedDomainTemplate");
 
-        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedNetwork, 
true);
-        validateVspNetwork(vspNetwork, false, true, false, false, 
"IsolatedDomainTemplate", true);
+        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedNetwork);
+        validateVspNetwork(vspNetwork, false, true, false, false, 
"IsolatedDomainTemplate");
 
-        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedNetwork, 
false);
-        validateVspNetwork(vspNetwork, false, true, false, false, 
"IsolatedDomainTemplate", false);
+        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedNetwork);
+        validateVspNetwork(vspNetwork, false, true, false, false, 
"IsolatedDomainTemplate");
 
-        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedVpcNetwork, 
true);
-        validateVspNetwork(vspNetwork, false, false, true, false, 
"VpcDomainTemplate", true);
+        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedVpcNetwork);
+        validateVspNetwork(vspNetwork, false, false, true, false, 
"VpcDomainTemplate");
 
-        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedVpcNetwork, 
false);
-        validateVspNetwork(vspNetwork, false, false, true, false, 
"VpcDomainTemplate", false);
+        vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(_mockedVpcNetwork);
+        validateVspNetwork(vspNetwork, false, false, true, false, 
"VpcDomainTemplate");
 
-        vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedSharedNetwork, true);
-        validateVspNetwork(vspNetwork, false, false, false, true, 
"SharedDomainTemplate", true);
+        vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedSharedNetwork);
+        validateVspNetwork(vspNetwork, false, false, false, true, 
"SharedDomainTemplate");
 
-        vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedSharedNetwork, false);
-        validateVspNetwork(vspNetwork, false, false, false, true, 
"SharedDomainTemplate", false);
+        vspNetwork = 
_nuageVspEntityBuilder.buildVspNetwork(_mockedSharedNetwork);
+        validateVspNetwork(vspNetwork, false, false, false, true, 
"SharedDomainTemplate");
     }
 
     @Test
@@ -219,7 +223,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
     }
 
     private void validateVspNetwork(VspNetwork vspNetwork, boolean isL2, 
boolean isL3, boolean isVpc, boolean isShared,
-            String domainTemplateName, boolean hasAddressRanges) {
+            String domainTemplateName) {
         assertEquals(NETWORK_ID, vspNetwork.getId());
         assertEquals("networkUuid", vspNetwork.getUuid());
         assertEquals("networkName", vspNetwork.getName());
@@ -245,22 +249,6 @@ public class NuageVspEntityBuilderTest extends NuageTest {
         assertEquals(domainTemplateName, vspNetwork.getDomainTemplateName());
         assertEquals("10.10.10.0/24", vspNetwork.getCidr());
         assertEquals("10.10.10.1", vspNetwork.getGateway());
-
-        if (hasAddressRanges) {
-            if (isShared) {
-                assertEquals("192.168.2.2", vspNetwork.getVirtualRouterIp());
-            } else {
-                assertEquals("10.10.10.2", vspNetwork.getVirtualRouterIp());
-            }
-
-            List<Pair<String, String>> ipAddressRanges;
-            if (isShared) {
-                ipAddressRanges = Lists.newArrayList(Pair.of("192.168.2.3", 
"192.168.2.200"));
-            } else {
-                ipAddressRanges = Lists.newArrayList(Pair.of("10.10.10.3", 
"10.10.10.254"));
-            }
-            assertEquals(ipAddressRanges, vspNetwork.getIpAddressRanges());
-        }
     }
 
     private void validateVspVm(VspVm vspVm, boolean isDomainRouter) {
@@ -289,7 +277,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
 
     private void validateVspAclRule(VspAclRule vspAclRule, boolean isFirewall) 
{
         assertEquals("aclUuid", vspAclRule.getUuid());
-        assertEquals("aclProtocol", vspAclRule.getProtocol());
+        assertEquals(Protocol.TCP, vspAclRule.getProtocol());
         assertEquals(new Integer(1), vspAclRule.getStartPort());
         assertEquals(new Integer(20), vspAclRule.getEndPort());
         assertEquals(Lists.newArrayList("10.10.0.0/16"), 
vspAclRule.getSourceCidrList());
@@ -358,12 +346,14 @@ public class NuageVspEntityBuilderTest extends NuageTest {
     private void setUpMockedNicProfile() {
         when(_mockedNicProfile.getMacAddress()).thenReturn("macAddress");
         when(_mockedNicProfile.getIPv4Address()).thenReturn("10.10.10.2");
+        when(_mockedNicProfile.getNetworkId()).thenReturn(NETWORK_ID);
     }
 
     private void setUpMockedNic() {
         when(_mockedNic.getUuid()).thenReturn("nicUuid");
         when(_mockedNic.getMacAddress()).thenReturn("macAddress");
         when(_mockedNic.getIPv4Address()).thenReturn("10.10.10.2");
+        when(_mockedNic.getNetworkId()).thenReturn(NETWORK_ID);
     }
 
     private void setUpMockedStaticNatIp() {
@@ -381,7 +371,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
 
     private void setUpMockedFirewallRule() {
         when(_mockedFirewallRule.getUuid()).thenReturn("aclUuid");
-        when(_mockedFirewallRule.getProtocol()).thenReturn("aclProtocol");
+        when(_mockedFirewallRule.getProtocol()).thenReturn("TCP");
         when(_mockedFirewallRule.getSourcePortStart()).thenReturn(1);
         when(_mockedFirewallRule.getSourcePortEnd()).thenReturn(20);
         
when(_mockedFirewallRule.getSourceCidrList()).thenReturn(Lists.newArrayList("10.10.0.0/16"));
@@ -392,7 +382,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
 
     private void setUpMockedNetworkAclItem() {
         when(_mockedNetworkAclItem.getUuid()).thenReturn("aclUuid");
-        when(_mockedNetworkAclItem.getProtocol()).thenReturn("aclProtocol");
+        when(_mockedNetworkAclItem.getProtocol()).thenReturn("TCP");
         when(_mockedNetworkAclItem.getSourcePortStart()).thenReturn(1);
         when(_mockedNetworkAclItem.getSourcePortEnd()).thenReturn(20);
         
when(_mockedNetworkAclItem.getSourceCidrList()).thenReturn(Lists.newArrayList("10.10.0.0/16"));
@@ -405,6 +395,7 @@ public class NuageVspEntityBuilderTest extends NuageTest {
     private void setUpMockedDaoCalls() {
         when(_domainDao.findById(DOMAIN_ID)).thenReturn(_mockedDomain);
         when(_accountDao.findById(ACCOUNT_ID)).thenReturn(_mockedAccount);
+        when(_networkDao.findById(NETWORK_ID)).thenReturn(_mockedNetwork);
         
when(_networkOfferingDao.findById(NETWORK_OFFERING_ID)).thenReturn(_mockedNetworkOffering);
         
when(_networkOfferingDao.findById(SHARED_NETWORK_OFFERING_ID)).thenReturn(_mockedSharedNetworkOffering);
         
when(_networkOfferingDao.findById(L2_NETWORK_OFFERING_ID)).thenReturn(_mockedL2NetworkOffering);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java 
b/server/src/com/cloud/api/ApiResponseHelper.java
index e661a9b..8563e1c 100644
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -1820,6 +1820,7 @@ public class ApiResponseHelper implements 
ResponseGenerator {
         response.setEgressDefaultPolicy(offering.getEgressDefaultPolicy());
         response.setConcurrentConnections(offering.getConcurrentConnections());
         response.setSupportsStrechedL2Subnet(offering.getSupportsStrechedL2());
+        response.setSupportsPublicAccess(offering.getSupportsPublicAccess());
         Long so = null;
         if (offering.getServiceOfferingId() != null) {
             so = offering.getServiceOfferingId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java 
b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 1fe973e..f33bd1a 100644
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -34,6 +34,9 @@ import java.util.UUID;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import com.google.common.base.MoreObjects;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
 import org.apache.log4j.Logger;
 
 import org.apache.cloudstack.acl.SecurityChecker;
@@ -158,7 +161,6 @@ import com.cloud.network.dao.PhysicalNetworkDao;
 import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
 import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.network.element.NetworkElement;
 import com.cloud.network.rules.LoadBalancerContainer.Scheme;
 import com.cloud.network.vpc.VpcManager;
 import com.cloud.offering.DiskOffering;
@@ -2851,16 +2853,16 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
                 String newVlanNetmask = newVlanNetmaskFinal;
                 String newVlanGateway = newVlanGatewayFinal;
 
-                if ((sameSubnet == null || sameSubnet.first() == false) && 
network.getTrafficType() == TrafficType.Guest && network.getGuestType() == 
GuestType.Shared
+                if ((sameSubnet == null || !sameSubnet.first()) && 
network.getTrafficType() == TrafficType.Guest && network.getGuestType() == 
GuestType.Shared
                         && _vlanDao.listVlansByNetworkId(networkId) != null) {
                     final Map<Capability, String> dhcpCapabilities = 
_networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()),
                             Service.Dhcp);
                     final String supportsMultipleSubnets = 
dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets);
                     if (supportsMultipleSubnets == null || 
!Boolean.valueOf(supportsMultipleSubnets)) {
-                        throw new  InvalidParameterValueException("The Dhcp 
serivice provider for this network dose not support the dhcp  across multiple 
subnets");
+                        throw new  InvalidParameterValueException("The dhcp 
service provider for this network does not support dhcp across multiple 
subnets");
                     }
                     s_logger.info("adding a new subnet to the network " + 
network.getId());
-                } else if (sameSubnet != null)  {
+                } else if (sameSubnet != null) {
                     // if it is same subnet the user might not send the vlan 
and the
                     // netmask details. so we are
                     // figuring out while validation and setting them here.
@@ -2876,13 +2878,13 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
         });
     }
 
-    public NetUtils.SupersetOrSubset checkIfSubsetOrSuperset(String 
newVlanGateway, String newVlanNetmask, final VlanVO vlan, final String startIP, 
final String endIP) {
+    public NetUtils.SupersetOrSubset checkIfSubsetOrSuperset(String 
vlanGateway, String vlanNetmask, String newVlanGateway, String newVlanNetmask, 
final String newStartIP, final String newEndIP) {
         if (newVlanGateway == null && newVlanNetmask == null) {
-            newVlanGateway = vlan.getVlanGateway();
-            newVlanNetmask = vlan.getVlanNetmask();
+            newVlanGateway = vlanGateway;
+            newVlanNetmask = vlanNetmask;
             // this means he is trying to add to the existing subnet.
-            if (NetUtils.sameSubnet(startIP, newVlanGateway, newVlanNetmask)) {
-                if (NetUtils.sameSubnet(endIP, newVlanGateway, 
newVlanNetmask)) {
+            if (NetUtils.sameSubnet(newStartIP, newVlanGateway, 
newVlanNetmask)) {
+                if (NetUtils.sameSubnet(newEndIP, newVlanGateway, 
newVlanNetmask)) {
                     return NetUtils.SupersetOrSubset.sameSubnet;
                 }
             }
@@ -2891,15 +2893,15 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
             throw new InvalidParameterValueException(
                     "either both netmask and gateway should be passed or both 
should me omited.");
         } else {
-            if (!NetUtils.sameSubnet(startIP, newVlanGateway, newVlanNetmask)) 
{
+            if (!NetUtils.sameSubnet(newStartIP, newVlanGateway, 
newVlanNetmask)) {
                 throw new InvalidParameterValueException("The start ip and 
gateway do not belong to the same subnet");
             }
-            if (!NetUtils.sameSubnet(endIP, newVlanGateway, newVlanNetmask)) {
+            if (!NetUtils.sameSubnet(newEndIP, newVlanGateway, 
newVlanNetmask)) {
                 throw new InvalidParameterValueException("The end ip and 
gateway do not belong to the same subnet");
             }
         }
         final String cidrnew = 
NetUtils.getCidrFromGatewayAndNetmask(newVlanGateway, newVlanNetmask);
-        final String existing_cidr = 
NetUtils.getCidrFromGatewayAndNetmask(vlan.getVlanGateway(), 
vlan.getVlanNetmask());
+        final String existing_cidr = 
NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask);
 
         return NetUtils.isNetowrkASubsetOrSupersetOfNetworkB(cidrnew, 
existing_cidr);
     }
@@ -2909,51 +2911,21 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
         String vlanGateway = null;
         String vlanNetmask = null;
         boolean sameSubnet = false;
-        if (vlans != null && vlans.size() > 0) {
+        if (CollectionUtils.isNotEmpty(vlans)) {
             for (final VlanVO vlan : vlans) {
-                if (ipv4) {
-                    vlanGateway = vlan.getVlanGateway();
-                    vlanNetmask = vlan.getVlanNetmask();
-                    // check if subset or super set or neither.
-                    final NetUtils.SupersetOrSubset val = 
checkIfSubsetOrSuperset(newVlanGateway, newVlanNetmask, vlan, startIP, endIP);
-                    if (val == NetUtils.SupersetOrSubset.isSuperset) {
-                        // this means that new cidr is a superset of the
-                        // existing subnet.
-                        throw new InvalidParameterValueException("The subnet 
you are trying to add is a superset of the existing subnet having gateway" + 
vlan.getVlanGateway()
-                                + " and netmask  " + vlan.getVlanNetmask());
-                    } else if (val == 
NetUtils.SupersetOrSubset.neitherSubetNorSuperset) {
-                        // this implies the user is trying to add a new subnet
-                        // which is not a superset or subset of this subnet.
-                        // checking with the other subnets.
-                        continue;
-                    } else if (val == NetUtils.SupersetOrSubset.isSubset) {
-                        // this means he is trying to add to the same subnet.
-                        throw new InvalidParameterValueException("The subnet 
you are trying to add is a subset of the existing subnet having gateway" + 
vlan.getVlanGateway()
-                                + " and netmask  " + vlan.getVlanNetmask());
-                    } else if (val == NetUtils.SupersetOrSubset.sameSubnet) {
-                        sameSubnet = true;
-                        //check if the gateway provided by the user is same as 
that of the subnet.
-                        if (newVlanGateway != null && 
!newVlanGateway.equals(vlanGateway)) {
-                            throw new InvalidParameterValueException("The 
gateway of the subnet should be unique. The subnet alreaddy has a gateway " + 
vlanGateway);
-                        }
-                        break;
-                    }
-                }
-                if (ipv6) {
-                    if (ip6Gateway != null && 
!ip6Gateway.equals(network.getIp6Gateway())) {
-                        throw new InvalidParameterValueException("The input 
gateway " + ip6Gateway + " is not same as network gateway " + 
network.getIp6Gateway());
-                    }
-                    if (ip6Cidr != null && 
!ip6Cidr.equals(network.getIp6Cidr())) {
-                        throw new InvalidParameterValueException("The input 
cidr " + ip6Cidr + " is not same as network ciddr " + network.getIp6Cidr());
-                    }
-                    ip6Gateway = network.getIp6Gateway();
-                    ip6Cidr = network.getIp6Cidr();
-                    _networkModel.checkIp6Parameters(startIPv6, endIPv6, 
ip6Gateway, ip6Cidr);
-                    sameSubnet = true;
-                }
+                vlanGateway = vlan.getVlanGateway();
+                vlanNetmask = vlan.getVlanNetmask();
+                sameSubnet = hasSameSubnet(ipv4, vlanGateway, vlanNetmask, 
newVlanGateway, newVlanNetmask, startIP, endIP,
+                        ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, 
network);
+                if (sameSubnet) break;
             }
+        } else {
+            vlanGateway = network.getGateway();
+            vlanNetmask = NetUtils.getCidrNetmask(network.getCidr());
+            sameSubnet = hasSameSubnet(ipv4, vlanGateway, vlanNetmask, 
newVlanGateway, newVlanNetmask, startIP, endIP,
+                    ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
         }
-        if (newVlanGateway == null && newVlanNetmask == null && sameSubnet == 
false) {
+        if (newVlanGateway == null && newVlanNetmask == null && !sameSubnet) {
             throw new InvalidParameterValueException("The ip range dose not 
belong to any of the existing subnets, Provide the netmask and gateway if you 
want to add new subnet");
         }
         Pair<String, String> vlanDetails = null;
@@ -2968,8 +2940,48 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
             throw new InvalidParameterValueException("The gateway ip should 
not be the part of the ip range being added.");
         }
 
-        final Pair<Boolean, Pair<String, String>> result = new Pair<Boolean, 
Pair<String, String>>(sameSubnet, vlanDetails);
-        return result;
+        return new Pair<Boolean, Pair<String, String>>(sameSubnet, 
vlanDetails);
+    }
+
+    public boolean hasSameSubnet(boolean ipv4, String vlanGateway, String 
vlanNetmask, String newVlanGateway, String newVlanNetmask, String newStartIp, 
String newEndIp,
+                                  boolean ipv6, String newIp6Gateway, String 
newIp6Cidr, String newIp6StartIp, String newIp6EndIp, Network network) {
+        if (ipv4) {
+            // check if subset or super set or neither.
+            final NetUtils.SupersetOrSubset val = 
checkIfSubsetOrSuperset(vlanGateway, vlanNetmask, newVlanGateway, 
newVlanNetmask, newStartIp, newEndIp);
+            if (val == NetUtils.SupersetOrSubset.isSuperset) {
+                // this means that new cidr is a superset of the
+                // existing subnet.
+                throw new InvalidParameterValueException("The subnet you are 
trying to add is a superset of the existing subnet having gateway " + 
vlanGateway
+                        + " and netmask " + vlanNetmask);
+            } else if (val == 
NetUtils.SupersetOrSubset.neitherSubetNorSuperset) {
+                // this implies the user is trying to add a new subnet
+                // which is not a superset or subset of this subnet.
+            } else if (val == NetUtils.SupersetOrSubset.isSubset) {
+                // this means he is trying to add to the same subnet.
+                throw new InvalidParameterValueException("The subnet you are 
trying to add is a subset of the existing subnet having gateway " + vlanGateway
+                        + " and netmask " + vlanNetmask);
+            } else if (val == NetUtils.SupersetOrSubset.sameSubnet) {
+                //check if the gateway provided by the user is same as that of 
the subnet.
+                if (newVlanGateway != null && 
!newVlanGateway.equals(vlanGateway)) {
+                    throw new InvalidParameterValueException("The gateway of 
the subnet should be unique. The subnet already has a gateway " + vlanGateway);
+                }
+                return true;
+            }
+        }
+        if (ipv6) {
+            if (newIp6Gateway != null && 
!newIp6Gateway.equals(network.getIp6Gateway())) {
+                throw new InvalidParameterValueException("The input gateway " 
+ newIp6Gateway + " is not same as network gateway " + network.getIp6Gateway());
+            }
+            if (newIp6Cidr != null && 
!newIp6Cidr.equals(network.getIp6Cidr())) {
+                throw new InvalidParameterValueException("The input cidr " + 
newIp6Cidr + " is not same as network cidr " + network.getIp6Cidr());
+            }
+
+            newIp6Gateway = MoreObjects.firstNonNull(newIp6Gateway, 
network.getIp6Gateway());
+            newIp6Cidr = MoreObjects.firstNonNull(newIp6Cidr, 
network.getIp6Cidr());
+            _networkModel.checkIp6Parameters(newIp6StartIp, newIp6EndIp, 
newIp6Gateway, newIp6Cidr);
+            return true;
+        }
+        return false;
     }
 
     @Override
@@ -3021,20 +3033,32 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
             }
         }
 
+
         // 1) if vlan is specified for the guest network range, it should be 
the
         // same as network's vlan
         // 2) if vlan is missing, default it to the guest network's vlan
         if (network.getTrafficType() == TrafficType.Guest) {
             String networkVlanId = null;
+            boolean connectivityWithoutVlan = false;
+            if (_networkModel.areServicesSupportedInNetwork(network.getId(), 
Service.Connectivity)) {
+                Map<Capability, String> connectivityCapabilities = 
_networkModel.getNetworkServiceCapabilities(network.getId(), 
Service.Connectivity);
+                connectivityWithoutVlan = 
MapUtils.isNotEmpty(connectivityCapabilities) && 
connectivityCapabilities.containsKey(Capability.NoVlan);
+            }
+
             final URI uri = network.getBroadcastUri();
-            if (uri != null) {
-                final String[] vlan = uri.toString().split("vlan:\\/\\/");
-                networkVlanId = vlan[1];
-                // For pvlan
-                networkVlanId = networkVlanId.split("-")[0];
+            if (connectivityWithoutVlan) {
+                networkVlanId = 
network.getBroadcastDomainType().toUri(network.getUuid()).toString();
+            } else if (uri != null) {
+                // Do not search for the VLAN tag when the network doesn't 
support VLAN
+               if (uri.toString().startsWith("vlan")) {
+                    final String[] vlan = uri.toString().split("vlan:\\/\\/");
+                    networkVlanId = vlan[1];
+                    // For pvlan
+                    networkVlanId = networkVlanId.split("-")[0];
+                }
             }
 
-            if (vlanId != null) {
+            if (vlanId != null && !connectivityWithoutVlan) {
                 // if vlan is specified, throw an error if it's not equal to
                 // network's vlanId
                 if (networkVlanId != null && 
!NetUtils.isSameIsolationId(networkVlanId, vlanId)) {
@@ -4068,7 +4092,7 @@ public class ConfigurationManagerImpl extends ManagerBase 
implements Configurati
             throw new InvalidParameterValueException("Capabilities for 
'Connectivity' service can be specified " +
                     "only when Connectivity service is enabled for network 
offering.");
         }
-        
validateConnectivityServiceCapablities(serviceProviderMap.get(Service.Connectivity),
 connectivityServiceCapabilityMap);
+        validateConnectivityServiceCapablities(guestType, 
serviceProviderMap.get(Service.Connectivity), connectivityServiceCapabilityMap);
 
         final Map<Service, Map<Capability, String>> serviceCapabilityMap = new 
HashMap<Service, Map<Capability, String>>();
         serviceCapabilityMap.put(Service.Lb, lbServiceCapabilityMap);
@@ -4210,15 +4234,18 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
         }
     }
 
-    void validateConnectivityServiceCapablities(final Set<Provider> providers, 
final Map<Capability, String> connectivityServiceCapabilityMap) {
+    void validateConnectivityServiceCapablities(final Network.GuestType 
guestType, final Set<Provider> providers, final Map<Capability, String> 
connectivityServiceCapabilityMap) {
         if (connectivityServiceCapabilityMap != null && 
!connectivityServiceCapabilityMap.isEmpty()) {
             for (final Map.Entry<Capability, String>entry: 
connectivityServiceCapabilityMap.entrySet()) {
                 final Capability capability = entry.getKey();
-                if (capability == Capability.StretchedL2Subnet) {
+                if (capability == Capability.StretchedL2Subnet || capability 
== Capability.PublicAccess) {
                     final String value = entry.getValue().toLowerCase();
                     if (!(value.contains("true") ^ value.contains("false"))) {
                         throw new InvalidParameterValueException("Invalid 
value (" + value + ") for " + capability +
                                 " should be true/false");
+                    } else if (capability == Capability.PublicAccess && 
guestType != GuestType.Shared) {
+                        throw new InvalidParameterValueException("Capability " 
+ capability.getName() + " can only be enabled for network offerings " +
+                                "with guest type Shared.");
                     }
                 } else {
                     throw new InvalidParameterValueException("Capability " + 
capability.getName() + " can not be "
@@ -4228,16 +4255,8 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
 
             // validate connectivity service provider actually supports 
specified capabilities
             if (providers != null && !providers.isEmpty()) {
-                for (final Provider provider: providers) {
-                    final NetworkElement element = 
_networkModel.getElementImplementingProvider(provider.getName());
-                    final Map<Service, Map<Capability, String>> capabilities = 
element.getCapabilities();
-                    if (capabilities != null && !capabilities.isEmpty()) {
-                        final Map<Capability, String> connectivityCapabilities 
=  capabilities.get(Service.Connectivity);
-                        if (connectivityCapabilities == null || 
connectivityCapabilities != null && 
!connectivityCapabilities.keySet().contains(Capability.StretchedL2Subnet)) {
-                            throw new 
InvalidParameterValueException("Provider: " + provider.getName() + " does not 
support "
-                                    + Capability.StretchedL2Subnet.getName());
-                        }
-                    }
+                for (Capability capability : 
connectivityServiceCapabilityMap.keySet()) {
+                    _networkModel.providerSupportsCapability(providers, 
Service.Connectivity, capability);
                 }
             }
         }
@@ -4255,7 +4274,10 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
 
         // specifyVlan should always be true for Shared network offerings
         if (!specifyVlan && type == GuestType.Shared) {
-            throw new InvalidParameterValueException("SpecifyVlan should be 
true if network offering's type is " + type);
+            Set<Provider> connectivityProviders = serviceProviderMap != null ? 
serviceProviderMap.get(Service.Connectivity) : null;
+            if (CollectionUtils.isEmpty(connectivityProviders) || 
!_networkModel.providerSupportsCapability(connectivityProviders, 
Service.Connectivity, Capability.NoVlan)) {
+                throw new InvalidParameterValueException("SpecifyVlan should 
be true if network offering's type is " + type);
+            }
         }
 
         // specifyIpRanges should always be true for Shared networks
@@ -4303,6 +4325,7 @@ public class ConfigurationManagerImpl extends ManagerBase 
implements Configurati
         boolean publicLb = false;
         boolean internalLb = false;
         boolean strechedL2Subnet = false;
+        boolean publicAccess = false;
 
         if (serviceCapabilityMap != null && !serviceCapabilityMap.isEmpty()) {
             final Map<Capability, String> lbServiceCapabilityMap = 
serviceCapabilityMap.get(Service.Lb);
@@ -4374,9 +4397,18 @@ public class ConfigurationManagerImpl extends 
ManagerBase implements Configurati
 
             final Map<Capability, String> connectivityServiceCapabilityMap = 
serviceCapabilityMap.get(Service.Connectivity);
             if (connectivityServiceCapabilityMap != null && 
!connectivityServiceCapabilityMap.isEmpty()) {
-                final String value = 
connectivityServiceCapabilityMap.get(Capability.StretchedL2Subnet);
-                if ("true".equalsIgnoreCase(value)) {
-                    strechedL2Subnet = true;
+                if 
(connectivityServiceCapabilityMap.containsKey(Capability.StretchedL2Subnet)) {
+                    final String value = 
connectivityServiceCapabilityMap.get(Capability.StretchedL2Subnet);
+                    if ("true".equalsIgnoreCase(value)) {
+                        strechedL2Subnet = true;
+                    }
+                }
+
+                if 
(connectivityServiceCapabilityMap.containsKey(Capability.PublicAccess)) {
+                    final String value = 
connectivityServiceCapabilityMap.get(Capability.PublicAccess);
+                    if ("true".equalsIgnoreCase(value)) {
+                        publicAccess = true;
+                    }
                 }
             }
         }
@@ -4388,7 +4420,7 @@ public class ConfigurationManagerImpl extends ManagerBase 
implements Configurati
 
         final NetworkOfferingVO offeringFinal = new NetworkOfferingVO(name, 
displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, 
isDefault, availability,
                 tags, type, conserveMode, dedicatedLb, sharedSourceNat, 
redundantRouter, elasticIp, elasticLb, specifyIpRanges, inline, isPersistent, 
associatePublicIp, publicLb,
-                internalLb, egressDefaultPolicy, strechedL2Subnet);
+                internalLb, egressDefaultPolicy, strechedL2Subnet, 
publicAccess);
 
         if (serviceOfferingId != null) {
             offeringFinal.setServiceOfferingId(serviceOfferingId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/network/NetworkModelImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkModelImpl.java 
b/server/src/com/cloud/network/NetworkModelImpl.java
index f3e25e8..131da26 100644
--- a/server/src/com/cloud/network/NetworkModelImpl.java
+++ b/server/src/com/cloud/network/NetworkModelImpl.java
@@ -1558,6 +1558,32 @@ public class NetworkModelImpl extends ManagerBase 
implements NetworkModel {
     }
 
     @Override
+    public boolean providerSupportsCapability(Set<Provider> providers, Service 
service, Capability cap) {
+        for (Provider provider : providers) {
+            NetworkElement element = 
getElementImplementingProvider(provider.getName());
+            if (element != null) {
+                Map<Service, Map<Capability, String>> elementCapabilities = 
element.getCapabilities();
+                if (elementCapabilities == null || 
!elementCapabilities.containsKey(service)) {
+                    throw new UnsupportedServiceException("Service " + 
service.getName() + " is not supported by the element=" + element.getName() +
+                            " implementing Provider=" + provider.getName());
+                }
+                Map<Capability, String> serviceCapabilities = 
elementCapabilities.get(service);
+                if (serviceCapabilities == null || 
serviceCapabilities.isEmpty()) {
+                    throw new UnsupportedServiceException("Service " + 
service.getName() + " doesn't have capabilites for element=" + 
element.getName() +
+                            " implementing Provider=" + provider.getName());
+                }
+
+                if (serviceCapabilities.containsKey(cap)) {
+                    return true;
+                }
+            } else {
+                throw new UnsupportedServiceException("Unable to find network 
element for provider " + provider.getName());
+            }
+        }
+        return false;
+    }
+
+    @Override
     public void checkCapabilityForProvider(Set<Provider> providers, Service 
service, Capability cap, String capValue) {
         for (Provider provider : providers) {
             NetworkElement element = 
getElementImplementingProvider(provider.getName());
@@ -1569,7 +1595,7 @@ public class NetworkModelImpl extends ManagerBase 
implements NetworkModel {
                 }
                 Map<Capability, String> serviceCapabilities = 
elementCapabilities.get(service);
                 if (serviceCapabilities == null || 
serviceCapabilities.isEmpty()) {
-                    throw new UnsupportedServiceException("Service " + 
service.getName() + " doesn't have capabilites for element=" + 
element.getName() +
+                    throw new UnsupportedServiceException("Service " + 
service.getName() + " doesn't have capabilities for element=" + 
element.getName() +
                         " implementing Provider=" + provider.getName());
                 }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/server/ConfigurationServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java 
b/server/src/com/cloud/server/ConfigurationServerImpl.java
index 13f98a2..0d6f6cd 100644
--- a/server/src/com/cloud/server/ConfigurationServerImpl.java
+++ b/server/src/com/cloud/server/ConfigurationServerImpl.java
@@ -1203,7 +1203,7 @@ public class ConfigurationServerImpl extends ManagerBase 
implements Configuratio
                 NetworkOfferingVO defaultNetscalerNetworkOffering =
                         new 
NetworkOfferingVO(NetworkOffering.DefaultSharedEIPandELBNetworkOffering,
                                 "Offering for Shared networks with Elastic IP 
and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true,
-                                Availability.Optional, null, 
Network.GuestType.Shared, true, false, false, false, true, true, true, false, 
false, true, true, false, false, false);
+                                Availability.Optional, null, 
Network.GuestType.Shared, true, false, false, false, true, true, true, false, 
false, true, true, false, false, false, false);
 
                 
defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled);
                 defaultNetscalerNetworkOffering = 
_networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/user/DomainManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/DomainManager.java 
b/server/src/com/cloud/user/DomainManager.java
index f72b18a..9bb2e01 100644
--- a/server/src/com/cloud/user/DomainManager.java
+++ b/server/src/com/cloud/user/DomainManager.java
@@ -49,5 +49,6 @@ public interface DomainManager extends DomainService {
     Domain updateDomain(UpdateDomainCmd cmd);
 
     public static final String MESSAGE_ADD_DOMAIN_EVENT = 
"Message.AddDomain.Event";
+    public static final String MESSAGE_PRE_REMOVE_DOMAIN_EVENT = 
"Message.PreRemoveDomain.Event";
     public static final String MESSAGE_REMOVE_DOMAIN_EVENT = 
"Message.RemoveDomain.Event";
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/src/com/cloud/user/DomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/DomainManagerImpl.java 
b/server/src/com/cloud/user/DomainManagerImpl.java
index 13dcd90..e8f0a50 100644
--- a/server/src/com/cloud/user/DomainManagerImpl.java
+++ b/server/src/com/cloud/user/DomainManagerImpl.java
@@ -301,6 +301,7 @@ public class DomainManagerImpl extends ManagerBase 
implements DomainManager, Dom
                     hasDedicatedResources = true;
                 }
                 if (accountsForCleanup.isEmpty() && networkIds.isEmpty() && 
!hasDedicatedResources) {
+                    _messageBus.publish(_name, 
MESSAGE_PRE_REMOVE_DOMAIN_EVENT, PublishScope.LOCAL, domain);
                     if (!_domainDao.remove(domain.getId())) {
                         rollBackState = true;
                         CloudRuntimeException e =
@@ -309,6 +310,7 @@ public class DomainManagerImpl extends ManagerBase 
implements DomainManager, Dom
                         e.addProxyObject(domain.getUuid(), "domainId");
                         throw e;
                     }
+                    _messageBus.publish(_name, MESSAGE_REMOVE_DOMAIN_EVENT, 
PublishScope.LOCAL, domain);
                 } else {
                     rollBackState = true;
                     String msg = null;
@@ -328,7 +330,6 @@ public class DomainManagerImpl extends ManagerBase 
implements DomainManager, Dom
 
             cleanupDomainOfferings(domain.getId());
             CallContext.current().putContextParameter(Domain.class, 
domain.getUuid());
-            _messageBus.publish(_name, MESSAGE_REMOVE_DOMAIN_EVENT, 
PublishScope.LOCAL, domain);
             return true;
         } catch (Exception ex) {
             s_logger.error("Exception deleting domain with id " + 
domain.getId(), ex);
@@ -363,8 +364,8 @@ public class DomainManagerImpl extends ManagerBase 
implements DomainManager, Dom
     private boolean cleanupDomain(Long domainId, Long ownerId) throws 
ConcurrentOperationException, ResourceUnavailableException {
         s_logger.debug("Cleaning up domain id=" + domainId);
         boolean success = true;
+        DomainVO domainHandle = _domainDao.findById(domainId);
         {
-            DomainVO domainHandle = _domainDao.findById(domainId);
             domainHandle.setState(Domain.State.Inactive);
             _domainDao.update(domainId, domainHandle);
 
@@ -452,7 +453,9 @@ public class DomainManagerImpl extends ManagerBase 
implements DomainManager, Dom
                 }
             }
             //delete domain
+            _messageBus.publish(_name, MESSAGE_PRE_REMOVE_DOMAIN_EVENT, 
PublishScope.LOCAL, domainHandle);
             deleteDomainSuccess = _domainDao.remove(domainId);
+            _messageBus.publish(_name, MESSAGE_REMOVE_DOMAIN_EVENT, 
PublishScope.LOCAL, domainHandle);
 
             // Delete resource count and resource limits entries set for this 
domain (if there are any).
             _resourceCountDao.removeEntriesByOwner(domainId, 
ResourceOwnerType.Domain);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/test/com/cloud/configuration/ConfigurationManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/configuration/ConfigurationManagerTest.java 
b/server/test/com/cloud/configuration/ConfigurationManagerTest.java
index 496b5a0..74f9ca2 100644
--- a/server/test/com/cloud/configuration/ConfigurationManagerTest.java
+++ b/server/test/com/cloud/configuration/ConfigurationManagerTest.java
@@ -23,6 +23,8 @@ import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyLong;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.lang.reflect.Field;
@@ -791,4 +793,72 @@ public class ConfigurationManagerTest {
 
         configurationMgr.checkIfZoneIsDeletable(new Random().nextLong());
     }
+
+    @Test
+    public void hasSameSubnetTest() {
+        //Ipv4 Test
+        boolean result;
+        result = configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, false, null, null, null, null, null);
+        Assert.assertFalse(result);
+        try {
+            configurationMgr.hasSameSubnet(true, "10.0.0.1", "255.255.255.0", 
"10.0.0.2", "255.255.255.0", "10.0.0.2", "10.0.0.10", false, null, null, null, 
null, null);
+            Assert.fail();
+        } catch (InvalidParameterValueException e) {
+            Assert.assertEquals(e.getMessage(), "The gateway of the subnet 
should be unique. The subnet already has a gateway 10.0.0.1");
+        }
+        try {
+            configurationMgr.hasSameSubnet(true, "10.0.0.1", "255.255.0.0", 
"10.0.0.2", "255.255.255.0", "10.0.0.2", "10.0.0.10", false, null, null, null, 
null, null);
+            Assert.fail();
+        } catch (InvalidParameterValueException e){
+            Assert.assertEquals(e.getMessage(), "The subnet you are trying to 
add is a subset of the existing subnet having gateway 10.0.0.1 and netmask 
255.255.0.0");
+        }
+        try {
+            configurationMgr.hasSameSubnet(true, "10.0.0.1", "255.255.255.0", 
"10.0.0.2", "255.255.0.0", "10.0.0.2", "10.0.0.10", false, null, null, null, 
null, null);
+            Assert.fail();
+        } catch (InvalidParameterValueException e) {
+            Assert.assertEquals(e.getMessage(), "The subnet you are trying to 
add is a superset of the existing subnet having gateway 10.0.0.1 and netmask 
255.255.255.0");
+        }
+        result = configurationMgr.hasSameSubnet(true, "10.0.0.1", 
"255.255.255.0", "10.0.0.1", "255.255.255.0", "10.0.0.2", "10.0.0.10", false, 
null, null, null, null, null);
+        Assert.assertTrue(result);
+
+        //Ipv6 Test
+        Network ipV6Network = mock(Network.class);
+        when(ipV6Network.getIp6Gateway()).thenReturn("2001:db8:0:f101::1");
+        when(ipV6Network.getIp6Cidr()).thenReturn("2001:db8:0:f101::0/64");
+        doThrow(new InvalidParameterValueException("Exception from Mock: 
startIPv6 is not in ip6cidr indicated 
network!")).when(configurationMgr._networkModel).checkIp6Parameters("2001:db9:0:f101::2",
 "2001:db9:0:f101::a", "2001:db8:0:f101::1", "2001:db8:0:f101::0/64");
+        doThrow(new InvalidParameterValueException("Exception from Mock: 
endIPv6 is not in ip6cidr indicated 
network!")).when(configurationMgr._networkModel).checkIp6Parameters("2001:db8:0:f101::a",
 "2001:db9:0:f101::2", "2001:db8:0:f101::1", "2001:db8:0:f101::0/64");
+        doThrow(new InvalidParameterValueException("ip6Gateway and ip6Cidr 
should be defined when startIPv6/endIPv6 are passed 
in")).when(configurationMgr._networkModel).checkIp6Parameters(Mockito.anyString(),
 Mockito.anyString(), Mockito.isNull(String.class), 
Mockito.isNull(String.class));
+
+
+        configurationMgr.hasSameSubnet(false, null, null, null, null, null, 
null, true, "2001:db8:0:f101::1", "2001:db8:0:f101::0/64", 
"2001:db8:0:f101::2", "2001:db8:0:f101::a", ipV6Network);
+        Assert.assertTrue(result);
+        try {
+            configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, true, "2001:db8:0:f101::2", "2001:db8:0:f101::0/64", 
"2001:db8:0:f101::2", "2001:db8:0:f101::a", ipV6Network);
+            Assert.fail();
+        } catch (InvalidParameterValueException e){
+            Assert.assertEquals(e.getMessage(), "The input gateway 
2001:db8:0:f101::2 is not same as network gateway 2001:db8:0:f101::1");
+        }
+        try {
+            configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, true, "2001:db8:0:f101::1", "2001:db8:0:f101::0/63", 
"2001:db8:0:f101::2", "2001:db8:0:f101::a", ipV6Network);
+            Assert.fail();
+        } catch (InvalidParameterValueException e){
+            Assert.assertEquals(e.getMessage(), "The input cidr 
2001:db8:0:f101::0/63 is not same as network cidr 2001:db8:0:f101::0/64");
+        }
+
+        try {
+            configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, true, "2001:db8:0:f101::1", "2001:db8:0:f101::0/64", 
"2001:db9:0:f101::2", "2001:db9:0:f101::a", ipV6Network);
+            Assert.fail();
+        } catch (InvalidParameterValueException e) {
+            Assert.assertEquals(e.getMessage(), "Exception from Mock: 
startIPv6 is not in ip6cidr indicated network!");
+        }
+        try {
+            configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, true, "2001:db8:0:f101::1", "2001:db8:0:f101::0/64", 
"2001:db8:0:f101::a", "2001:db9:0:f101::2", ipV6Network);
+            Assert.fail();
+        } catch(InvalidParameterValueException e){
+            Assert.assertEquals(e.getMessage(), "Exception from Mock: endIPv6 
is not in ip6cidr indicated network!");
+        }
+
+        result = configurationMgr.hasSameSubnet(false, null, null, null, null, 
null, null, true, null, null, "2001:db8:0:f101::2", "2001:db8:0:f101::a", 
ipV6Network);
+        Assert.assertTrue(result);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/test/com/cloud/network/CreatePrivateNetworkTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/CreatePrivateNetworkTest.java 
b/server/test/com/cloud/network/CreatePrivateNetworkTest.java
index 2e6cfa1..8a7b54c 100644
--- a/server/test/com/cloud/network/CreatePrivateNetworkTest.java
+++ b/server/test/com/cloud/network/CreatePrivateNetworkTest.java
@@ -103,7 +103,7 @@ public class CreatePrivateNetworkTest {
 
         NetworkOfferingVO ntwkOff =
             new NetworkOfferingVO("offer", "fakeOffer", TrafficType.Guest, 
true, true, null, null, false, null, null, GuestType.Isolated, false, false, 
false, false,
-                false, false, false, false, false, false, false, false, false, 
false);
+                false, false, false, false, false, false, false, false, false, 
false, false);
         
when(networkService._networkOfferingDao.findById(anyLong())).thenReturn(ntwkOff);
         List<NetworkOfferingVO> netofferlist = new 
ArrayList<NetworkOfferingVO>();
         netofferlist.add(ntwkOff);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/test/com/cloud/network/MockNetworkModelImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/MockNetworkModelImpl.java 
b/server/test/com/cloud/network/MockNetworkModelImpl.java
index c00d83f..f3d1f38 100644
--- a/server/test/com/cloud/network/MockNetworkModelImpl.java
+++ b/server/test/com/cloud/network/MockNetworkModelImpl.java
@@ -491,6 +491,11 @@ public class MockNetworkModelImpl extends ManagerBase 
implements NetworkModel {
         return false;
     }
 
+    @Override
+    public boolean providerSupportsCapability(Set<Provider> providers, Service 
service, Capability cap) {
+        return false;
+    }
+
     /* (non-Javadoc)
      * @see 
com.cloud.network.NetworkModel#checkCapabilityForProvider(java.util.Set, 
com.cloud.network.Network.Service, com.cloud.network.Network.Capability, 
java.lang.String)
      */

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/test/com/cloud/network/NetworkModelTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/NetworkModelTest.java 
b/server/test/com/cloud/network/NetworkModelTest.java
index 55f620b..ba57542 100644
--- a/server/test/com/cloud/network/NetworkModelTest.java
+++ b/server/test/com/cloud/network/NetworkModelTest.java
@@ -19,11 +19,17 @@ package com.cloud.network;
 
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyLong;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.spy;
 
 import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 import junit.framework.Assert;
 
@@ -32,13 +38,16 @@ import org.junit.Test;
 
 import com.cloud.dc.VlanVO;
 import com.cloud.dc.dao.VlanDao;
+import com.cloud.exception.UnsupportedServiceException;
 import com.cloud.network.dao.IPAddressDao;
 import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.element.NetworkElement;
 import com.cloud.user.Account;
 import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.net.Ip;
+import com.cloud.network.Network.Provider;
 
 public class NetworkModelTest {
     @Before
@@ -77,4 +86,53 @@ public class NetworkModelTest {
 
     }
 
+    @Test
+    public void testCapabilityForProvider() {
+        NetworkModelImpl modelImpl = spy(NetworkModelImpl.class);
+        Set<Provider> providers = new HashSet<>();
+        providers.add(Provider.NuageVsp);
+        NetworkElement nuageVspElement = mock(NetworkElement.class);
+        HashMap<Network.Service, Map<Network.Capability, String>> nuageVspCap 
= new HashMap<Network.Service, Map<Network.Capability, String>>();
+        HashMap<Network.Capability, String> nuageVspConnectivity = new 
HashMap<Network.Capability, String>();
+        nuageVspConnectivity.put(Network.Capability.NoVlan, "FindMe");
+        nuageVspConnectivity.put(Network.Capability.PublicAccess, "");
+
+        nuageVspCap.put(Network.Service.Connectivity, nuageVspConnectivity);
+        when(nuageVspElement.getName()).thenReturn("NuageVsp");
+        doReturn(nuageVspCap).when(nuageVspElement).getCapabilities();
+        
doReturn(nuageVspElement).when(modelImpl).getElementImplementingProvider("NuageVsp");
+
+        try {
+            modelImpl.checkCapabilityForProvider(providers, 
Network.Service.UserData, null, null);
+            Assert.fail();
+        } catch (UnsupportedServiceException e) {
+            Assert.assertEquals(e.getMessage(), "Service " + 
Network.Service.UserData.getName() + " is not supported by the element=NuageVsp 
implementing Provider=" + Provider.NuageVsp.getName());
+        }
+
+        try {
+            modelImpl.checkCapabilityForProvider(providers, 
Network.Service.Connectivity, Network.Capability.ElasticIp, null);
+            Assert.fail();
+        } catch (UnsupportedServiceException e) {
+            Assert.assertEquals(e.getMessage(), "Service " + 
Network.Service.Connectivity.getName() + " doesn't have capability " + 
Network.Capability.ElasticIp.getName() + " for element=NuageVsp implementing 
Provider=" + Provider.NuageVsp.getName());
+        }
+        try {
+            modelImpl.checkCapabilityForProvider(providers, 
Network.Service.Connectivity, Network.Capability.PublicAccess, 
"NonExistingVal");
+            Assert.fail();
+        } catch (UnsupportedServiceException e){
+            Assert.assertEquals(e.getMessage(),"Service Connectivity doesn't 
have capability PublicAccess for element=NuageVsp implementing 
Provider=NuageVsp");
+        }
+
+        modelImpl.checkCapabilityForProvider(providers, 
Network.Service.Connectivity, Network.Capability.NoVlan, "FindMe");
+
+        NetworkElement nuageVspElement2 = mock(NetworkElement.class);
+        doReturn(null).when(nuageVspElement).getCapabilities();
+        try {
+            modelImpl.checkCapabilityForProvider(providers, 
Network.Service.Connectivity, Network.Capability.PublicAccess, "");
+            Assert.fail();
+        } catch (UnsupportedServiceException e) {
+            Assert.assertEquals(e.getMessage(), "Service Connectivity is not 
supported by the element=NuageVsp implementing Provider=NuageVsp");
+        }
+    }
+
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/server/test/com/cloud/vpc/MockNetworkModelImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vpc/MockNetworkModelImpl.java 
b/server/test/com/cloud/vpc/MockNetworkModelImpl.java
index 93b31e9..89a7ab7 100644
--- a/server/test/com/cloud/vpc/MockNetworkModelImpl.java
+++ b/server/test/com/cloud/vpc/MockNetworkModelImpl.java
@@ -508,9 +508,14 @@ public class MockNetworkModelImpl extends ManagerBase 
implements NetworkModel {
         return false;
     }
 
+    @Override
+    public boolean providerSupportsCapability(Set<Provider> providers, Service 
service, Capability cap) {
+        return false;
+    }
+
     /* (non-Javadoc)
-     * @see 
com.cloud.network.NetworkModel#checkCapabilityForProvider(java.util.Set, 
com.cloud.network.Network.Service, com.cloud.network.Network.Capability, 
java.lang.String)
-     */
+         * @see 
com.cloud.network.NetworkModel#checkCapabilityForProvider(java.util.Set, 
com.cloud.network.Network.Service, com.cloud.network.Network.Capability, 
java.lang.String)
+         */
     @Override
     public void checkCapabilityForProvider(Set<Provider> providers, Service 
service, Capability cap, String capValue) {
         // TODO Auto-generated method stub

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/setup/db/db/schema-4910to41000.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-4910to41000.sql 
b/setup/db/db/schema-4910to41000.sql
index 127d7f8..beabe96 100644
--- a/setup/db/db/schema-4910to41000.sql
+++ b/setup/db/db/schema-4910to41000.sql
@@ -45,4 +45,6 @@ CREATE TABLE `cloud`.`vlan_details` (
   `display` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Should detail be displayed 
to the end user',
   PRIMARY KEY (`id`),
   CONSTRAINT `fk_vlan_details__vlan_id` FOREIGN KEY 
`fk_vlan_details__vlan_id`(`vlan_id`) REFERENCES `vlan`(`id`) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
\ No newline at end of file
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+ALTER TABLE `cloud`.`network_offerings` ADD COLUMN supports_public_access 
boolean default false;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4c91c9c5/test/integration/plugins/nuagevsp/nuageTestCase.py
----------------------------------------------------------------------
diff --git a/test/integration/plugins/nuagevsp/nuageTestCase.py 
b/test/integration/plugins/nuagevsp/nuageTestCase.py
index 530dced..1a11fd6 100644
--- a/test/integration/plugins/nuagevsp/nuageTestCase.py
+++ b/test/integration/plugins/nuagevsp/nuageTestCase.py
@@ -19,7 +19,8 @@
 """
 # Import Local Modules
 from marvin.cloudstackTestCase import cloudstackTestCase, unittest
-from marvin.lib.base import (EgressFireWallRule,
+from marvin.lib.base import (Domain,
+                             EgressFireWallRule,
                              FireWallRule,
                              Host,
                              Hypervisor,
@@ -36,7 +37,8 @@ from marvin.lib.base import (EgressFireWallRule,
                              StaticNATRule,
                              VirtualMachine,
                              VPC,
-                             VpcOffering)
+                             VpcOffering,
+                             Zone)
 from marvin.lib.common import (get_domain,
                                get_template,
                                get_zone)
@@ -84,11 +86,18 @@ class nuageTestCase(cloudstackTestCase):
         # We want to fail quicker, if it's a failure
         socket.setdefaulttimeout(60)
 
+        # Get test client and test data
         cls.test_client = super(nuageTestCase, cls).getClsTestClient()
         cls.api_client = cls.test_client.getApiClient()
         cls.db_client = cls.test_client.getDbConnection()
         cls.test_data = cls.test_client.getParsedTestDataConfig()
 
+        # Get Zones and Domains
+        cls.zones = Zone.list(cls.api_client)
+        cls.domains = Domain.list(cls.api_client, listall=True)
+        cls.domain = get_domain(cls.api_client)
+        cls.root_domain = get_domain(cls.api_client, domain_name="ROOT")
+
         # Get Zone details
         cls.getZoneDetails()
 
@@ -106,12 +115,11 @@ class nuageTestCase(cloudstackTestCase):
 
     @classmethod
     def getZoneDetails(cls, zone=None):
-        # Get Zone, Domain and templates
+        # Get Zone details
         cls.zone = zone if zone else get_zone(
             cls.api_client,
             zone_name=cls.test_client.getZoneForTests()
         )
-        cls.domain = get_domain(cls.api_client)
         cls.template = get_template(cls.api_client,
                                     cls.zone.id,
                                     cls.test_data["ostype"]
@@ -160,35 +168,34 @@ class nuageTestCase(cloudstackTestCase):
         # Get data center Internet connectivity information from the Marvin
         # config file, which is required to perform Internet connectivity and
         # traffic tests from the guest VMs.
-        cls.isInternetConnectivityAvailable = False
-        cls.http_proxy = None
-        cls.https_proxy = None
-        dc_internet_conn_info = cls.config.dcInternetConnectivityInfo if \
-            cls.config.dcInternetConnectivityInfo else None
-        if dc_internet_conn_info:
-            dc_internet_conn_available = dc_internet_conn_info.available if \
-                dc_internet_conn_info.available else None
-            if dc_internet_conn_available:
-                cls.isInternetConnectivityAvailable = True if \
-                    dc_internet_conn_available == "true" else False
-            dc_internet_conn_http_proxy = dc_internet_conn_info.httpProxy if \
-                dc_internet_conn_info.httpProxy else None
-            if dc_internet_conn_http_proxy:
-                cls.http_proxy = dc_internet_conn_http_proxy
-            dc_internet_conn_https_proxy = dc_internet_conn_info.httpsProxy \
-                if dc_internet_conn_info.httpsProxy else None
-            if dc_internet_conn_https_proxy:
-                cls.https_proxy = dc_internet_conn_https_proxy
+        cls.dcInternetConnectivityInfo()
 
         # Check if the configured Nuage VSP SDN platform infrastructure
         # supports underlay networking
         cmd = listNuageUnderlayVlanIpRanges.listNuageUnderlayVlanIpRangesCmd()
+        cmd.zoneid = cls.zone.id
         cmd.underlay = True
         cls.isNuageInfraUnderlay = isinstance(
             cls.api_client.listNuageUnderlayVlanIpRanges(cmd), list)
         return
 
     @classmethod
+    def dcInternetConnectivityInfo(cls):
+        cls.isInternetConnectivityAvailable = False
+        cls.http_proxy = None
+        cls.https_proxy = None
+        zone = next(zone for zone in cls.config.zones
+                    if zone.name == cls.zone.name)
+        if zone.dcInternetConnectivityInfo.available:
+            cls.isInternetConnectivityAvailable = \
+                zone.dcInternetConnectivityInfo.available == "true"
+        if cls.isInternetConnectivityAvailable:
+            if zone.dcInternetConnectivityInfo.httpProxy:
+                cls.http_proxy = zone.dcInternetConnectivityInfo.httpProxy
+            if zone.dcInternetConnectivityInfo.httpsProxy:
+                cls.https_proxy = zone.dcInternetConnectivityInfo.httpsProxy
+
+    @classmethod
     def configureVSDSessions(cls):
         # VSD is a programmable policy and analytics engine of Nuage VSP SDN
         # platform; vspk is a Python SDK for Nuage VSP's VSD; libVSD is a
@@ -906,6 +913,66 @@ class nuageTestCase(cloudstackTestCase):
         self.debug("Successfully verified the creation and state of Network "
                    "- %s in VSD" % network.name)
 
+    # get_subnet_id - Calculates and returns the subnet ID in VSD with the
+    # given CloudStack network ID and subnet gateway
+    def get_subnet_id(self, network_id, gateway):
+        try:
+            import uuid
+
+            class NULL_NAMESPACE:
+                bytes = b''
+            # The UUID of the shared network in ACS
+            # The gateway IP of the address range
+            network_id = str(network_id)
+            bytes = bytearray(network_id)
+            ipbytes = bytearray(gateway)
+            subnet_id = uuid.uuid3(NULL_NAMESPACE, bytes + ipbytes)
+            self.debug("The required subnet id is %s in VSD" % subnet_id)
+            return str(subnet_id)
+        except Exception as e:
+            self.debug("Failed to get the subnet id due to %s" % e)
+            self.fail("Unable to get the subnet id, failing the test case")
+
+    # verify_vsd_shared_network - Verifies the given CloudStack domain and
+    # shared network against the corresponding installed enterprise, domain,
+    # zone, subnet, and shared network resource in VSD
+    def verify_vsd_shared_network(self, domain_id, network,
+                                  gateway="10.1.1.1"):
+        self.debug("Verifying the creation and state of Shared Network - %s "
+                   "in VSD" % network.name)
+        vsd_enterprise = self.vsd.get_enterprise(
+            filter=self.get_externalID_filter(domain_id))
+        ext_network_id_filter = self.get_externalID_filter(network.id)
+        vsd_domain = self.vsd.get_domain(filter=ext_network_id_filter)
+        vsd_zone = self.vsd.get_zone(filter=ext_network_id_filter)
+        subnet_id = self.get_subnet_id(network.id, gateway)
+        vsd_subnet = self.vsd.get_subnet(
+            filter=self.get_externalID_filter(subnet_id))
+        self.assertNotEqual(vsd_enterprise, None,
+                            "VSD enterprise (CloudStack domain) data format "
+                            "should not be of type None"
+                            )
+        self.assertEqual(vsd_domain.description, network.name,
+                         "VSD domain description should match network name in "
+                         "CloudStack"
+                         )
+        self.assertEqual(vsd_zone.description, network.name,
+                         "VSD zone description should match network name in "
+                         "CloudStack"
+                         )
+        self.assertEqual(vsd_subnet.description, network.name,
+                         "VSD subnet description '%s' should match network "
+                         "name in CloudStack" % vsd_subnet.description
+                         )
+        shared_resource = self.vsd.get_shared_network_resource(
+            filter=self.get_externalID_filter(subnet_id))
+        self.assertEqual(shared_resource.description, network.name,
+                         "VSD shared resources description should match "
+                         "network name in CloudStack"
+                         )
+        self.debug("Successfully verified the creation and state of Shared "
+                   "Network - %s in VSD" % network.name)
+
     # verify_vsd_object_status - Verifies the given CloudStack object status in
     # VSD
     def verify_vsd_object_status(self, cs_object, stopped):
@@ -914,7 +981,7 @@ class nuageTestCase(cloudstackTestCase):
         expected_status = cs_object.state.upper() if not stopped \
             else "DELETE_PENDING"
         tries = 0
-        while (vsd_object.status != expected_status) and (tries < 3):
+        while (vsd_object.status != expected_status) and (tries < 10):
             self.debug("Waiting for the CloudStack object " + cs_object.name +
                        " to be fully resolved in VSD...")
             time.sleep(30)
@@ -957,6 +1024,82 @@ class nuageTestCase(cloudstackTestCase):
         self.debug("Successfully verified the deployment and state of VM - %s "
                    "in VSD" % vm.name)
 
+    # verify_vsd_enterprise_vm - Verifies the given CloudStack domain VM
+    # deployment and status in the corresponding VSD enterprise
+    def verify_vsd_enterprise_vm(self, domain_id, network, vm, vpc=None,
+                                 stopped=False, sharedsubnetid=None):
+        self.debug("Verifying the creation and state of Network - %s in VSD" %
+                   network.name)
+        vsd_enterprise = self.vsd.get_enterprise(
+            filter=self.get_externalID_filter(domain_id))
+        ext_network_id_filter = self.get_externalID_filter(vpc.id) if vpc \
+            else self.get_externalID_filter(network.id)
+        vsd_domain = self.vsd.get_domain(
+            enterprise=vsd_enterprise, filter=ext_network_id_filter)
+        vsd_zone = self.vsd.get_zone(
+            domain=vsd_domain, filter=ext_network_id_filter)
+        if sharedsubnetid:
+            vsd_subnet = self.vsd.get_subnet(
+                zone=vsd_zone,
+                filter=self.get_externalID_filter(sharedsubnetid))
+        else:
+            vsd_subnet = self.vsd.get_subnet(
+                zone=vsd_zone, filter=self.get_externalID_filter(network.id))
+        self.assertNotEqual(vsd_enterprise, None,
+                            "VSD enterprise (CloudStack domain) data format "
+                            "should not be of type None"
+                            )
+        if vpc:
+            self.assertEqual(vsd_domain.description, "VPC_" + vpc.name,
+                             "VSD domain description should match VPC name in "
+                             "CloudStack"
+                             )
+            self.assertEqual(vsd_zone.description, "VPC_" + vpc.name,
+                             "VSD zone description should match VPC name in "
+                             "CloudStack"
+                             )
+        else:
+            self.assertEqual(vsd_domain.description, network.name,
+                             "VSD domain description should match network "
+                             "name in CloudStack"
+                             )
+            self.assertEqual(vsd_zone.description, network.name,
+                             "VSD zone description should match network name "
+                             "in CloudStack"
+                             )
+        self.assertEqual(vsd_subnet.description, network.name,
+                         "VSD subnet description '%s' should match network "
+                         "name in CloudStack" % vsd_subnet.description
+                         )
+        self.debug("Successfully verified the creation and state of Network - "
+                   "%s in VSD" % network.name)
+        self.debug("Verifying the deployment and state of VM - %s in VSD" %
+                   vm.name)
+        vsd_vm = self.vsd.get_vm(
+            subnet=vsd_subnet, filter=self.get_externalID_filter(vm.id))
+        self.assertNotEqual(vsd_vm, None,
+                            "VM data format in VSD should not be of type None"
+                            )
+        vm_info = VirtualMachine.list(self.api_client, id=vm.id)[0]
+        for nic in vm_info.nic:
+            if nic.networkid == network.id:
+                vsd_vport = self.vsd.get_vport(
+                    subnet=vsd_subnet,
+                    filter=self.get_externalID_filter(nic.id))
+                vsd_vm_interface = self.vsd.get_vm_interface(
+                    filter=self.get_externalID_filter(nic.id))
+                self.assertEqual(vsd_vport.active, True,
+                                 "VSD VM vport should be active"
+                                 )
+                self.assertEqual(vsd_vm_interface.ip_address, nic.ipaddress,
+                                 "VSD VM interface IP address should match "
+                                 "VM's NIC IP address in CloudStack"
+                                 )
+        if not self.isSimulator:
+            self.verify_vsd_object_status(vm, stopped)
+        self.debug("Successfully verified the deployment and state of VM - %s "
+                   "in VSD" % vm.name)
+
     # verify_vsd_router - Verifies the given CloudStack network router
     # deployment and status in VSD
     def verify_vsd_router(self, router, stopped=False):

Reply via email to