cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bfede...@apache.org
Subject [24/50] [abbrv] Squashed commit of the following:
Date Tue, 16 Apr 2013 18:03:57 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
new file mode 100644
index 0000000..52f0ea6
--- /dev/null
+++ b/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java
@@ -0,0 +1,232 @@
+/*
+ * $HeadURL$
+ * $Revision$
+ * $Date$
+ * 
+ * ====================================================================
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.httpclient.contrib.ssl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.UnknownHostException;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+
+import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.HttpClientError;
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * <p>
+ * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s 
+ * that accept self-signed certificates. 
+ * </p>
+ * <p>
+ * This socket factory SHOULD NOT be used for productive systems 
+ * due to security reasons, unless it is a concious decision and 
+ * you are perfectly aware of security implications of accepting 
+ * self-signed certificates
+ * </p>
+ *
+ * <p>
+ * Example of using custom protocol socket factory for a specific host:
+ *     <pre>
+ *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
+ *
+ *     URI uri = new URI("https://localhost/", true);
+ *     // use relative url only
+ *     GetMethod httpget = new GetMethod(uri.getPathQuery());
+ *     HostConfiguration hc = new HostConfiguration();
+ *     hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
+ *     HttpClient client = new HttpClient();
+ *     client.executeMethod(hc, httpget);
+ *     </pre>
+ * </p>
+ * <p>
+ * Example of using custom protocol socket factory per default instead of the standard one:
+ *     <pre>
+ *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
+ *     Protocol.registerProtocol("https", easyhttps);
+ *
+ *     HttpClient client = new HttpClient();
+ *     GetMethod httpget = new GetMethod("https://localhost/");
+ *     client.executeMethod(httpget);
+ *     </pre>
+ * </p>
+ * 
+ * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
+ * 
+ * <p>
+ * DISCLAIMER: HttpClient developers DO NOT actively support this component.
+ * The component is provided as a reference material, which may be inappropriate
+ * for use without additional customization.
+ * </p>
+ */
+
+public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory {
+
+    /** Log object for this class. */
+    private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class);
+
+    private SSLContext sslcontext = null;
+
+    /**
+     * Constructor for EasySSLProtocolSocketFactory.
+     */
+    public EasySSLProtocolSocketFactory() {
+        super();
+    }
+
+    private static SSLContext createEasySSLContext() {
+        try {
+            SSLContext context = SSLContext.getInstance("SSL");
+            context.init(
+              null, 
+              new TrustManager[] {new EasyX509TrustManager(null)}, 
+              null);
+            return context;
+        } catch (Exception e) {
+            LOG.error(e.getMessage(), e);
+            throw new HttpClientError(e.toString());
+        }
+    }
+
+    private SSLContext getSSLContext() {
+        if (this.sslcontext == null) {
+            this.sslcontext = createEasySSLContext();
+        }
+        return this.sslcontext;
+    }
+
+    /**
+     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
+     */
+    public Socket createSocket(
+        String host,
+        int port,
+        InetAddress clientHost,
+        int clientPort)
+        throws IOException, UnknownHostException {
+
+        return getSSLContext().getSocketFactory().createSocket(
+            host,
+            port,
+            clientHost,
+            clientPort
+        );
+    }
+
+    /**
+     * Attempts to get a new socket connection to the given host within the given time limit.
+     * <p>
+     * To circumvent the limitations of older JREs that do not support connect timeout a 
+     * controller thread is executed. The controller thread attempts to create a new socket 
+     * within the given limit of time. If socket constructor does not return until the 
+     * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
+     * </p>
+     *  
+     * @param host the host name/IP
+     * @param port the port on the host
+     * @param clientHost the local host name/IP to bind the socket to
+     * @param clientPort the port on the local machine
+     * @param params {@link HttpConnectionParams Http connection parameters}
+     * 
+     * @return Socket a new socket
+     * 
+     * @throws IOException if an I/O error occurs while creating the socket
+     * @throws UnknownHostException if the IP address of the host cannot be
+     * determined
+     */
+    public Socket createSocket(
+        final String host,
+        final int port,
+        final InetAddress localAddress,
+        final int localPort,
+        final HttpConnectionParams params
+    ) throws IOException, UnknownHostException, ConnectTimeoutException {
+        if (params == null) {
+            throw new IllegalArgumentException("Parameters may not be null");
+        }
+        int timeout = params.getConnectionTimeout();
+        SocketFactory socketfactory = getSSLContext().getSocketFactory();
+        if (timeout == 0) {
+            return socketfactory.createSocket(host, port, localAddress, localPort);
+        } else {
+            Socket socket = socketfactory.createSocket();
+            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
+            SocketAddress remoteaddr = new InetSocketAddress(host, port);
+            socket.bind(localaddr);
+            socket.connect(remoteaddr, timeout);
+            return socket;
+        }
+    }
+
+    /**
+     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
+     */
+    public Socket createSocket(String host, int port)
+        throws IOException, UnknownHostException {
+        return getSSLContext().getSocketFactory().createSocket(
+            host,
+            port
+        );
+    }
+
+    /**
+     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
+     */
+    public Socket createSocket(
+        Socket socket,
+        String host,
+        int port,
+        boolean autoClose)
+        throws IOException, UnknownHostException {
+        return getSSLContext().getSocketFactory().createSocket(
+            socket,
+            host,
+            port,
+            autoClose
+        );
+    }
+
+    public boolean equals(Object obj) {
+        return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class));
+    }
+
+    public int hashCode() {
+        return EasySSLProtocolSocketFactory.class.hashCode();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
new file mode 100644
index 0000000..ae9f938
--- /dev/null
+++ b/plugins/network-elements/cisco-vnmc/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java
@@ -0,0 +1,114 @@
+/*
+ * ====================================================================
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.httpclient.contrib.ssl;
+
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import org.apache.commons.logging.Log; 
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * <p>
+ * EasyX509TrustManager unlike default {@link X509TrustManager} accepts 
+ * self-signed certificates. 
+ * </p>
+ * <p>
+ * This trust manager SHOULD NOT be used for productive systems 
+ * due to security reasons, unless it is a concious decision and 
+ * you are perfectly aware of security implications of accepting 
+ * self-signed certificates
+ * </p>
+ * 
+ * @author <a href="mailto:adrian.sutton@ephox.com">Adrian Sutton</a>
+ * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * 
+ * <p>
+ * DISCLAIMER: HttpClient developers DO NOT actively support this component.
+ * The component is provided as a reference material, which may be inappropriate
+ * for use without additional customization.
+ * </p>
+ */
+
+public class EasyX509TrustManager implements X509TrustManager
+{
+    private X509TrustManager standardTrustManager = null;
+
+    /** Log object for this class. */
+    private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class);
+
+    /**
+     * Constructor for EasyX509TrustManager.
+     */
+    public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
+        super();
+        TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+        factory.init(keystore);
+        TrustManager[] trustmanagers = factory.getTrustManagers();
+        if (trustmanagers.length == 0) {
+            throw new NoSuchAlgorithmException("no trust manager found");
+        }
+        this.standardTrustManager = (X509TrustManager)trustmanagers[0];
+    }
+
+    /**
+     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
+     */
+    public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
+        standardTrustManager.checkClientTrusted(certificates,authType);
+    }
+
+    /**
+     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
+     */
+    public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
+        if ((certificates != null) && LOG.isDebugEnabled()) {
+            LOG.debug("Server certificate chain:");
+            for (int i = 0; i < certificates.length; i++) {
+                LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
+            }
+        }
+        if ((certificates != null) && (certificates.length == 1)) {
+            certificates[0].checkValidity();
+        } else {
+            standardTrustManager.checkServerTrusted(certificates,authType);
+        }
+    }
+
+    /**
+     * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
+     */
+    public X509Certificate[] getAcceptedIssuers() {
+        return this.standardTrustManager.getAcceptedIssuers();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/network-elements/cisco-vnmc/test/com/cloud/network/cisco/CiscoVnmcConnectionTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/cisco-vnmc/test/com/cloud/network/cisco/CiscoVnmcConnectionTest.java b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/cisco/CiscoVnmcConnectionTest.java
new file mode 100644
index 0000000..bf52356
--- /dev/null
+++ b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/cisco/CiscoVnmcConnectionTest.java
@@ -0,0 +1,248 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the 
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.cisco;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Map;
+
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.cloud.network.cisco.CiscoVnmcConnectionImpl;
+import com.cloud.utils.exception.ExecutionException;
+
+
+@Ignore("Requires actual VNMC to connect to")
+public class CiscoVnmcConnectionTest {
+    static CiscoVnmcConnectionImpl connection;
+    static String tenantName = "TenantE";
+    static Map<String, String> fwDns = null;
+
+    @BeforeClass
+    public static void setUpClass() throws Exception {
+        connection = new CiscoVnmcConnectionImpl("10.223.56.5", "admin", "C1sco123");
+        try {
+            boolean response = connection.login();
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    
+    @Test
+    public void testLogin() {
+        //fail("Not yet implemented");
+        try {
+            boolean response = connection.login();
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    
+    @Test
+    public void testCreateTenant() {
+        //fail("Not yet implemented");
+        try {
+            boolean response = connection.createTenant(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDC() {
+        //fail("Not yet implemented");
+        try {
+            boolean response = connection.createTenantVDC(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCEdgeDeviceProfile() {
+        //fail("Not yet implemented");
+        try {
+            boolean response = connection.createTenantVDCEdgeDeviceProfile(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCEdgeDeviceRoutePolicy() {
+        try {
+            boolean response = connection.createTenantVDCEdgeStaticRoutePolicy(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCEdgeDeviceRoute() {
+        try {
+            boolean response = connection.createTenantVDCEdgeStaticRoute(tenantName,
+                    "10.223.136.1", "0.0.0.0", "0.0.0.0");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testAssociateRoutePolicyWithEdgeProfile() {
+        try {
+            boolean response = connection.associateTenantVDCEdgeStaticRoutePolicy(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testAssociateTenantVDCEdgeDhcpPolicy() {
+        try {
+            boolean response = connection.associateTenantVDCEdgeDhcpPolicy(tenantName, "Edge_Inside");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCEdgeDhcpPolicy() {
+        try {
+            boolean response = connection.createTenantVDCEdgeDhcpPolicy(tenantName,
+                    "10.1.1.2", "10.1.1.254", "255.255.255.0","4.4.4.4", tenantName+ ".net");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCEdgeSecurityProfile() {
+        try {
+            boolean response = connection.createTenantVDCEdgeSecurityProfile(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCSourceNatIpPool() {
+        try {
+            boolean response = connection.createTenantVDCSourceNatIpPool(tenantName, "1", "10.223.136.10");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCSourceNatPolicy() {
+        try {
+            boolean response = connection.createTenantVDCSourceNatPolicy(tenantName, "1");
+            assertTrue(response);
+            response = connection.createTenantVDCSourceNatPolicyRef(tenantName, "1");
+            assertTrue(response);
+            response = connection.createTenantVDCSourceNatRule(tenantName, "1", "10.1.1.2", "10.1.1.254");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateTenantVDCNatPolicySet() {
+        try {
+            boolean response = connection.createTenantVDCNatPolicySet(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testAssociateNatPolicySet() {
+        try {
+            boolean response = connection.associateNatPolicySet(tenantName);
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testCreateEdgeFirewall() {
+        try {
+            boolean response = connection.createEdgeFirewall(tenantName,
+                    "44.44.44.44", "192.168.1.1", "255.255.255.0", "255.255.255.192");
+            assertTrue(response);
+        } catch (ExecutionException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void testListUnassocAsa1000v() {
+        try {
+            Map<String, String> response = connection.listUnAssocAsa1000v();
+            assertTrue(response.size() >=0);
+            fwDns = response;
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void assocAsa1000v() {
+        try {
+            boolean result = connection.assignAsa1000v(tenantName, fwDns.get(0));
+            assertTrue(result);
+        } catch (ExecutionException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/network-elements/cisco-vnmc/test/com/cloud/network/element/CiscoVnmcElementTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/cisco-vnmc/test/com/cloud/network/element/CiscoVnmcElementTest.java b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/element/CiscoVnmcElementTest.java
new file mode 100755
index 0000000..a16733b
--- /dev/null
+++ b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/element/CiscoVnmcElementTest.java
@@ -0,0 +1,401 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.element;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.naming.ConfigurationException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.internal.matchers.Any;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.AssociateAsaWithLogicalEdgeFirewallCommand;
+import com.cloud.agent.api.CleanupLogicalEdgeFirewallCommand;
+import com.cloud.agent.api.ConfigureNexusVsmForAsaCommand;
+import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand;
+import com.cloud.agent.api.routing.SetFirewallRulesCommand;
+import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
+import com.cloud.agent.api.routing.SetSourceNatCommand;
+import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.dc.ClusterVSMMapVO;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.VlanVO;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.dao.ClusterVSMMapDao;
+import com.cloud.dc.dao.VlanDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.domain.Domain;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.Network;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.CiscoNexusVSMDeviceVO;
+import com.cloud.network.IpAddress;
+import com.cloud.network.NetworkManager;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.addr.PublicIp;
+import com.cloud.network.cisco.CiscoAsa1000vDeviceVO;
+import com.cloud.network.cisco.CiscoVnmcControllerVO;
+import com.cloud.network.cisco.NetworkAsa1000vMapVO;
+import com.cloud.network.dao.CiscoAsa1000vDao;
+import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
+import com.cloud.network.dao.CiscoVnmcDao;
+import com.cloud.network.dao.NetworkAsa1000vMapDao;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.StaticNat;
+import com.cloud.network.rules.StaticNatRule;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.resource.ResourceManager;
+import com.cloud.user.Account;
+import com.cloud.utils.net.Ip;
+import com.cloud.vm.ReservationContext;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+public class CiscoVnmcElementTest {
+
+    CiscoVnmcElement _element = new CiscoVnmcElement();
+    AgentManager _agentMgr = mock(AgentManager.class);
+    NetworkManager _networkMgr = mock(NetworkManager.class);
+    NetworkModel _networkModel = mock(NetworkModel.class);
+    HostDao _hostDao = mock(HostDao.class);
+    NetworkServiceMapDao _ntwkSrvcDao = mock(NetworkServiceMapDao.class);
+    ConfigurationManager _configMgr = mock(ConfigurationManager.class);
+    CiscoVnmcDao _ciscoVnmcDao = mock(CiscoVnmcDao.class);
+    CiscoAsa1000vDao _ciscoAsa1000vDao = mock(CiscoAsa1000vDao.class);
+    NetworkAsa1000vMapDao _networkAsa1000vMapDao = mock(NetworkAsa1000vMapDao.class);
+    ClusterVSMMapDao _clusterVsmMapDao = mock(ClusterVSMMapDao.class);
+    CiscoNexusVSMDeviceDao _vsmDeviceDao = mock(CiscoNexusVSMDeviceDao.class);
+    VlanDao _vlanDao = mock(VlanDao.class);
+
+    @Before
+    public void setUp() throws ConfigurationException {
+        _element._resourceMgr = mock(ResourceManager.class);
+        _element._agentMgr = _agentMgr;
+        _element._networkMgr = _networkMgr;
+        _element._networkModel = _networkModel;
+        _element._hostDao = _hostDao;
+        _element._configMgr = _configMgr;
+        _element._ciscoVnmcDao = _ciscoVnmcDao;
+        _element._ciscoAsa1000vDao = _ciscoAsa1000vDao;
+        _element._networkAsa1000vMapDao = _networkAsa1000vMapDao;
+        _element._clusterVsmMapDao = _clusterVsmMapDao;
+        _element._vsmDeviceDao = _vsmDeviceDao;
+        _element._vlanDao = _vlanDao;
+
+        // Standard responses
+        when(_networkModel.isProviderForNetwork(Provider.CiscoVnmc, 1L)).thenReturn(true);
+
+        _element.configure("CiscoVnmcTestElement", Collections.<String, Object> emptyMap());
+    }
+
+    @Test
+    public void canHandleTest() {
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        assertTrue(_element.canHandle(network));
+
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.UnDecided);
+        assertFalse(_element.canHandle(network));
+    }
+
+    @Test
+    public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+    	URI uri = URI.create("vlan://123");
+
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        when(network.getDataCenterId()).thenReturn(1L);
+        when(network.getGateway()).thenReturn("1.1.1.1");
+        when(network.getBroadcastUri()).thenReturn(uri);
+        when(network.getCidr()).thenReturn("1.1.1.0/24");
+
+        NetworkOffering offering = mock(NetworkOffering.class);
+        when(offering.getId()).thenReturn(1L);
+        when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+        when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+
+        DeployDestination dest = mock(DeployDestination.class);
+
+        Domain dom = mock(Domain.class);
+        when(dom.getName()).thenReturn("d1");
+        Account acc = mock(Account.class);
+        when(acc.getAccountName()).thenReturn("a1");
+        ReservationContext context = mock(ReservationContext.class);
+        when(context.getDomain()).thenReturn(dom);
+        when(context.getAccount()).thenReturn(acc);
+
+        DataCenter dc = mock(DataCenter.class);
+        when(dc.getNetworkType()).thenReturn(NetworkType.Advanced);
+        when(_configMgr.getZone(network.getDataCenterId())).thenReturn(dc);
+
+        List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
+        devices.add(mock(CiscoVnmcControllerVO.class));
+        when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
+
+        CiscoAsa1000vDeviceVO asaVO = mock(CiscoAsa1000vDeviceVO.class);
+        when(asaVO.getInPortProfile()).thenReturn("foo");
+        when(asaVO.getManagementIp()).thenReturn("1.2.3.4");
+
+        List<CiscoAsa1000vDeviceVO> asaList = new ArrayList<CiscoAsa1000vDeviceVO>();
+        asaList.add(asaVO);
+        when(_ciscoAsa1000vDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(asaList);
+
+        when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
+        when(_networkAsa1000vMapDao.findByAsa1000vId(anyLong())).thenReturn(null);
+        when(_networkAsa1000vMapDao.persist(any(NetworkAsa1000vMapVO.class))).thenReturn(mock(NetworkAsa1000vMapVO.class));
+
+        when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.CiscoVnmc)).thenReturn(true);
+
+        ClusterVSMMapVO clusterVsmMap = mock(ClusterVSMMapVO.class);
+        when(_clusterVsmMapDao.findByClusterId(anyLong())).thenReturn(clusterVsmMap);
+
+        CiscoNexusVSMDeviceVO vsmDevice = mock(CiscoNexusVSMDeviceVO.class);
+        when(vsmDevice.getUserName()).thenReturn("foo");
+        when(vsmDevice.getPassword()).thenReturn("bar");
+        when(vsmDevice.getipaddr()).thenReturn("1.2.3.4");
+        when(_vsmDeviceDao.findById(anyLong())).thenReturn(vsmDevice);
+
+        HostVO hostVO = mock(HostVO.class);
+        when(hostVO.getId()).thenReturn(1L);
+        when(_hostDao.findById(anyLong())).thenReturn(hostVO);
+
+        Ip ip = mock(Ip.class);
+        when(ip.addr()).thenReturn("1.2.3.4");
+
+        PublicIp publicIp = mock(PublicIp.class);
+        when(publicIp.getAddress()).thenReturn(ip);
+        when(publicIp.getState()).thenReturn(IpAddress.State.Releasing);
+        when(publicIp.getAccountId()).thenReturn(1L);
+        when(publicIp.isSourceNat()).thenReturn(true);
+        when(publicIp.getVlanTag()).thenReturn("123");
+        when(publicIp.getGateway()).thenReturn("1.1.1.1");
+        when(publicIp.getNetmask()).thenReturn("1.1.1.1");
+        when(publicIp.getMacAddress()).thenReturn(null);
+        when(publicIp.isOneToOneNat()).thenReturn(true);
+        when(_networkMgr.assignSourceNatIpAddressToGuestNetwork(acc, network)).thenReturn(publicIp);
+
+        VlanVO vlanVO = mock(VlanVO.class);
+        when(vlanVO.getVlanGateway()).thenReturn("1.1.1.1");
+        List<VlanVO> vlanVOList = new ArrayList<VlanVO>();
+        when(_vlanDao.listVlansByPhysicalNetworkId(network.getPhysicalNetworkId())).thenReturn(vlanVOList);
+
+        Answer answer = mock(Answer.class);
+        when(answer.getResult()).thenReturn(true);
+
+        when(_agentMgr.easySend(anyLong(), any(CreateLogicalEdgeFirewallCommand.class))).thenReturn(answer);
+        when(_agentMgr.easySend(anyLong(), any(ConfigureNexusVsmForAsaCommand.class))).thenReturn(answer);
+        when(_agentMgr.easySend(anyLong(), any(SetSourceNatCommand.class))).thenReturn(answer);
+        when(_agentMgr.easySend(anyLong(), any(AssociateAsaWithLogicalEdgeFirewallCommand.class))).thenReturn(answer);
+        
+        assertTrue(_element.implement(network, offering, dest, context));
+    }
+
+    @Test
+    public void shutdownTest() throws ConcurrentOperationException, ResourceUnavailableException {
+    	URI uri = URI.create("vlan://123");
+
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        when(network.getDataCenterId()).thenReturn(1L);
+        when(network.getBroadcastUri()).thenReturn(uri);
+
+        ReservationContext context = mock(ReservationContext.class);
+
+        when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
+
+        List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
+        devices.add(mock(CiscoVnmcControllerVO.class));
+        when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
+
+        HostVO hostVO = mock(HostVO.class);
+        when(hostVO.getId()).thenReturn(1L);
+        when(_hostDao.findById(anyLong())).thenReturn(hostVO);
+
+        Answer answer = mock(Answer.class);
+        when(answer.getResult()).thenReturn(true);
+
+        when(_agentMgr.easySend(anyLong(), any(CleanupLogicalEdgeFirewallCommand.class))).thenReturn(answer);
+
+    	assertTrue(_element.shutdown(network, context, true));
+    }
+
+    @Test
+    public void applyFWRulesTest() throws ResourceUnavailableException {
+    	URI uri = URI.create("vlan://123");
+
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        when(network.getDataCenterId()).thenReturn(1L);
+        when(network.getBroadcastUri()).thenReturn(uri);
+        when(network.getCidr()).thenReturn("1.1.1.0/24");
+        when(network.getState()).thenReturn(Network.State.Implemented);
+
+        Ip ip = mock(Ip.class);
+        when(ip.addr()).thenReturn("1.2.3.4");
+
+        IpAddress ipAddress = mock(IpAddress.class);
+        when(ipAddress.getAddress()).thenReturn(ip);
+
+        when(_networkModel.getIp(anyLong())).thenReturn(ipAddress);
+        when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, Provider.CiscoVnmc)).thenReturn(true);
+
+        List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
+        devices.add(mock(CiscoVnmcControllerVO.class));
+        when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
+
+        when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
+
+        HostVO hostVO = mock(HostVO.class);
+        when(hostVO.getId()).thenReturn(1L);
+        when(_hostDao.findById(anyLong())).thenReturn(hostVO);
+
+        FirewallRule rule = mock(FirewallRule.class);
+        when(rule.getSourceIpAddressId()).thenReturn(1L);
+        List<FirewallRule> rules = new ArrayList<FirewallRule>();
+        rules.add(rule);
+
+        Answer answer = mock(Answer.class);
+        when(answer.getResult()).thenReturn(true);
+
+        when(_agentMgr.easySend(anyLong(), any(SetFirewallRulesCommand.class))).thenReturn(answer);
+
+        assertTrue(_element.applyFWRules(network, rules));
+    }
+
+    @Test
+    public void applyPRulesTest() throws ResourceUnavailableException {
+    	URI uri = URI.create("vlan://123");
+
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        when(network.getDataCenterId()).thenReturn(1L);
+        when(network.getBroadcastUri()).thenReturn(uri);
+        when(network.getCidr()).thenReturn("1.1.1.0/24");
+        when(network.getState()).thenReturn(Network.State.Implemented);
+
+        Ip ip = mock(Ip.class);
+        when(ip.addr()).thenReturn("1.2.3.4");
+
+        IpAddress ipAddress = mock(IpAddress.class);
+        when(ipAddress.getAddress()).thenReturn(ip);
+        when(ipAddress.getVlanId()).thenReturn(1L);
+
+        when(_networkModel.getIp(anyLong())).thenReturn(ipAddress);
+        when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, Provider.CiscoVnmc)).thenReturn(true);
+
+        List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
+        devices.add(mock(CiscoVnmcControllerVO.class));
+        when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
+
+        when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
+
+        HostVO hostVO = mock(HostVO.class);
+        when(hostVO.getId()).thenReturn(1L);
+        when(_hostDao.findById(anyLong())).thenReturn(hostVO);
+
+        VlanVO vlanVO = mock(VlanVO.class);
+        when(vlanVO.getVlanTag()).thenReturn(null);
+        when(_vlanDao.findById(anyLong())).thenReturn(vlanVO);
+
+        PortForwardingRule rule = mock(PortForwardingRule.class);
+        when(rule.getSourceIpAddressId()).thenReturn(1L);
+        when(rule.getDestinationIpAddress()).thenReturn(ip);
+        List<PortForwardingRule> rules = new ArrayList<PortForwardingRule>();
+        rules.add(rule);
+
+        Answer answer = mock(Answer.class);
+        when(answer.getResult()).thenReturn(true);
+
+        when(_agentMgr.easySend(anyLong(), any(SetPortForwardingRulesCommand.class))).thenReturn(answer);
+
+        assertTrue(_element.applyPFRules(network, rules));
+    }
+
+    @Test
+    public void applyStaticNatsTest() throws ResourceUnavailableException {
+    	URI uri = URI.create("vlan://123");
+
+        Network network = mock(Network.class);
+        when(network.getId()).thenReturn(1L);
+        when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
+        when(network.getDataCenterId()).thenReturn(1L);
+        when(network.getBroadcastUri()).thenReturn(uri);
+        when(network.getCidr()).thenReturn("1.1.1.0/24");
+        when(network.getState()).thenReturn(Network.State.Implemented);
+
+        Ip ip = mock(Ip.class);
+        when(ip.addr()).thenReturn("1.2.3.4");
+
+        IpAddress ipAddress = mock(IpAddress.class);
+        when(ipAddress.getAddress()).thenReturn(ip);
+        when(ipAddress.getVlanId()).thenReturn(1L);
+
+        when(_networkModel.getIp(anyLong())).thenReturn(ipAddress);
+        when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.StaticNat, Provider.CiscoVnmc)).thenReturn(true);
+
+        List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
+        devices.add(mock(CiscoVnmcControllerVO.class));
+        when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
+
+        when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
+
+        HostVO hostVO = mock(HostVO.class);
+        when(hostVO.getId()).thenReturn(1L);
+        when(_hostDao.findById(anyLong())).thenReturn(hostVO);
+
+        VlanVO vlanVO = mock(VlanVO.class);
+        when(vlanVO.getVlanTag()).thenReturn(null);
+        when(_vlanDao.findById(anyLong())).thenReturn(vlanVO);
+
+        StaticNat rule = mock(StaticNat.class);
+        when(rule.getSourceIpAddressId()).thenReturn(1L);
+        when(rule.getDestIpAddress()).thenReturn("1.2.3.4");
+        when(rule.isForRevoke()).thenReturn(false);
+        List<StaticNat> rules = new ArrayList<StaticNat>();
+        rules.add(rule);
+
+        Answer answer = mock(Answer.class);
+        when(answer.getResult()).thenReturn(true);
+
+        when(_agentMgr.easySend(anyLong(), any(SetStaticNatRulesCommand.class))).thenReturn(answer);
+
+        assertTrue(_element.applyStaticNats(network, rules));
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/network-elements/cisco-vnmc/test/com/cloud/network/resource/CiscoVnmcResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/cisco-vnmc/test/com/cloud/network/resource/CiscoVnmcResourceTest.java b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/resource/CiscoVnmcResourceTest.java
new file mode 100755
index 0000000..e814fdc
--- /dev/null
+++ b/plugins/network-elements/cisco-vnmc/test/com/cloud/network/resource/CiscoVnmcResourceTest.java
@@ -0,0 +1,285 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.resource;
+
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand;
+import com.cloud.agent.api.PingCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.routing.NetworkElementCommand;
+import com.cloud.agent.api.routing.SetFirewallRulesCommand;
+import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
+import com.cloud.agent.api.routing.SetSourceNatCommand;
+import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
+import com.cloud.agent.api.to.FirewallRuleTO;
+import com.cloud.agent.api.to.IpAddressTO;
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+import com.cloud.agent.api.to.StaticNatRuleTO;
+import com.cloud.dc.Vlan;
+import com.cloud.host.Host;
+import com.cloud.network.IpAddress;
+import com.cloud.network.cisco.CiscoVnmcConnectionImpl;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.StaticNat;
+import com.cloud.network.rules.FirewallRule.Purpose;
+import com.cloud.network.rules.FirewallRule.TrafficType;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.utils.exception.ExecutionException;
+
+public class CiscoVnmcResourceTest {
+    CiscoVnmcConnectionImpl _connection = mock(CiscoVnmcConnectionImpl.class);
+    CiscoVnmcResource _resource;
+    Map<String,Object> _parameters;
+
+    @Before
+    public void setUp() throws ConfigurationException {
+        _resource = new CiscoVnmcResource();
+
+        _parameters = new HashMap<String, Object>();
+        _parameters.put("name", "CiscoVnmc");
+        _parameters.put("zoneId", "1");
+        _parameters.put("physicalNetworkId", "100");
+        _parameters.put("ip", "1.2.3.4");
+        _parameters.put("username", "admin");
+        _parameters.put("password", "pass");
+        _parameters.put("guid", "e8e13097-0a08-4e82-b0af-1101589ec3b8");
+        _parameters.put("numretries", "3");
+        _parameters.put("timeout", "300");
+    }
+
+    @Test(expected=ConfigurationException.class)
+    public void resourceConfigureFailure() throws ConfigurationException {
+        _resource.configure("CiscoVnmcResource", Collections.<String,Object>emptyMap());
+    }
+
+    @Test
+    public void resourceConfigure() throws ConfigurationException {
+        _resource.configure("CiscoVnmcResource", _parameters);
+        assertTrue("CiscoVnmc".equals(_resource.getName()));
+        assertTrue(_resource.getType() == Host.Type.ExternalFirewall);
+    }
+
+    @Test
+    public void testInitialization() throws ConfigurationException {
+        _resource.configure("CiscoVnmcResource", _parameters);
+        StartupCommand[] sc = _resource.initialize();
+        assertTrue(sc.length ==1);
+        assertTrue("e8e13097-0a08-4e82-b0af-1101589ec3b8".equals(sc[0].getGuid()));
+        assertTrue("CiscoVnmc".equals(sc[0].getName()));
+        assertTrue("1".equals(sc[0].getDataCenter()));
+    }
+
+    @Test
+    public void testPingCommandStatusOk() throws ConfigurationException, ExecutionException {
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.login()).thenReturn(true);
+        PingCommand ping = _resource.getCurrentStatus(1);
+        assertTrue(ping != null);
+        assertTrue(ping.getHostId() == 1);
+        assertTrue(ping.getHostType() == Host.Type.ExternalFirewall);
+    }
+
+    @Test
+    public void testPingCommandStatusFail() throws ConfigurationException, ExecutionException {
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.login()).thenReturn(false);
+        PingCommand ping = _resource.getCurrentStatus(1);
+        assertTrue(ping == null);
+    }
+
+    @Test
+    public void testSourceNat() throws ConfigurationException, Exception {
+        long vlanId = 123;
+        IpAddressTO ip = new IpAddressTO(1, "1.2.3.4", true, false,
+                false, null, "1.2.3.1", "255.255.255.0", null, null, false);
+        SetSourceNatCommand cmd = new SetSourceNatCommand(ip, true);
+        cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId));
+        cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32");
+
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.login()).thenReturn(true);
+        when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCSourceNatPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCSourceNatPolicyRef(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCSourceNatIpPool(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCSourceNatRule(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.associateNatPolicySet(anyString())).thenReturn(true);
+
+        Answer answer = _resource.executeRequest(cmd);
+        System.out.println(answer.getDetails());
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testFirewall() throws ConfigurationException, Exception {
+        long vlanId = 123;
+        List<FirewallRuleTO> rules = new ArrayList<FirewallRuleTO>();
+        List<String> cidrList = new ArrayList<String>();
+        cidrList.add("2.3.2.3/32");
+        FirewallRuleTO active = new FirewallRuleTO(1,
+                null, "1.2.3.4", "tcp", 22, 22, false, false,
+                FirewallRule.Purpose.Firewall, cidrList, null, null);
+        rules.add(active);
+        FirewallRuleTO revoked = new FirewallRuleTO(1,
+                null, "1.2.3.4", "tcp", 22, 22, true, false,
+                FirewallRule.Purpose.Firewall, null, null, null);
+        rules.add(revoked);
+
+        SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rules);
+        cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId));
+        cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32");
+
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.deleteTenantVDCAclRule(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCIngressAclRule(
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCEgressAclRule(
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.associateAclPolicySet(anyString())).thenReturn(true);
+
+        Answer answer = _resource.executeRequest(cmd);
+        System.out.println(answer.getDetails());
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testStaticNat() throws ConfigurationException, Exception {
+        long vlanId = 123;
+        List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
+        StaticNatRuleTO active = new StaticNatRuleTO(0, "1.2.3.4", null,
+                null, "5.6.7.8", null, null, null, false, false);
+        rules.add(active);
+        StaticNatRuleTO revoked = new StaticNatRuleTO(0, "1.2.3.4", null, 
+                null, "5.6.7.8", null, null, null, true, false);
+        rules.add(revoked);
+
+        SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rules, null);
+        cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId));
+        cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32");
+
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.createTenantVDCDNatPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCDNatPolicyRef(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.deleteTenantVDCDNatRule(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.deleteTenantVDCAclRule(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCDNatIpPool(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCDNatRule(anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclRuleForDNat(anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.associateAclPolicySet(anyString())).thenReturn(true);
+
+        Answer answer = _resource.executeRequest(cmd);
+        System.out.println(answer.getDetails());
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testPortForwarding() throws ConfigurationException, Exception {
+        long vlanId = 123;
+        List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
+        PortForwardingRuleTO active = new PortForwardingRuleTO(1, "1.2.3.4", 22, 22,
+                "5.6.7.8", 22, 22, "tcp", false, false);
+        rules.add(active);
+        PortForwardingRuleTO revoked = new PortForwardingRuleTO(1, "1.2.3.4", 22, 22,
+                "5.6.7.8", 22, 22, "tcp", false, false);
+        rules.add(revoked);
+
+        SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(rules);
+        cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId));
+        cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32");
+
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.createTenantVDCPFPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCPFPolicyRef(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true);
+        when(_connection.deleteTenantVDCPFRule(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.deleteTenantVDCAclRule(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCPFIpPool(anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCPFPortPool(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCPFRule(anyString(),
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.createTenantVDCAclRuleForPF(anyString(),
+                anyString(), anyString(), anyString(),
+                anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.associateAclPolicySet(anyString())).thenReturn(true);
+
+        Answer answer = _resource.executeRequest(cmd);
+        System.out.println(answer.getDetails());
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testCreateEdgeFirewall() throws ConfigurationException, Exception {
+        long vlanId = 123;
+        CreateLogicalEdgeFirewallCommand cmd = new CreateLogicalEdgeFirewallCommand(vlanId, "1.2.3.4", "5.6.7.8", "255.255.255.0", "255.255.255.0");
+        cmd.getPublicGateways().add("1.1.1.1");
+        cmd.getPublicGateways().add("2.2.2.2");
+
+        _resource.configure("CiscoVnmcResource", _parameters);
+        _resource.setConnection(_connection);
+        when(_connection.createTenant(anyString())).thenReturn(true);
+        when(_connection.createTenantVDC(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCEdgeSecurityProfile(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCEdgeDeviceProfile(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCEdgeStaticRoutePolicy(anyString())).thenReturn(true);
+        when(_connection.createTenantVDCEdgeStaticRoute(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+        when(_connection.associateTenantVDCEdgeStaticRoutePolicy(anyString())).thenReturn(true);
+        when(_connection.createEdgeFirewall(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+
+        Answer answer = _resource.executeRequest(cmd);
+        System.out.println(answer.getDetails());
+        assertTrue(answer.getResult());
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/plugins/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/pom.xml b/plugins/pom.xml
index 12c85ff..471253f 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -138,6 +138,7 @@
       </activation>
       <modules>
         <module>hypervisors/vmware</module>
+        <module>network-elements/cisco-vnmc</module>
       </modules>
     </profile>
     <profile>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/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 50c137a..cfe0e00 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -2717,8 +2717,8 @@ public class ApiResponseHelper implements ResponseGenerator {
         List<? extends Network.Provider> serviceProviders = ApiDBUtils.getProvidersForService(service);
         List<ProviderResponse> serviceProvidersResponses = new ArrayList<ProviderResponse>();
         for (Network.Provider serviceProvider : serviceProviders) {
-            // return only Virtual Router/JuniperSRX as a provider for the firewall
-            if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX)) {
+            // return only Virtual Router/JuniperSRX/CiscoVnmc as a provider for the firewall
+            if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX || serviceProvider == Provider.CiscoVnmc)) {
                 continue;
             }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/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 fce3c01..5b6d81e 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -3302,8 +3302,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                             throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr);
                         }
 
-                        if (provider == Provider.JuniperSRX) {
-                            firewallProvider = Provider.JuniperSRX;
+                        if (provider == Provider.JuniperSRX || provider == Provider.CiscoVnmc) {
+                            firewallProvider = provider;
                         }
                         
                         if ((service == Service.PortForwarding || service == Service.StaticNat) && provider == Provider.VirtualRouter){

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/setup/db/db/schema-410to420.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-410to420.sql b/setup/db/db/schema-410to420.sql
index 92b2d9c..fb760bf 100644
--- a/setup/db/db/schema-410to420.sql
+++ b/setup/db/db/schema-410to420.sql
@@ -680,7 +680,41 @@ CREATE VIEW `cloud`.`affinity_group_view` AS
             left join
         `cloud`.`vm_instance` ON vm_instance.id = affinity_group_vm_map.instance_id
             left join
-		`cloud`.`user_vm` ON user_vm.id = vm_instance.id;
-		
+        `cloud`.`user_vm` ON user_vm.id = vm_instance.id;
+
+CREATE TABLE `cloud`.`external_cisco_vnmc_devices` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
+  `uuid` varchar(255) UNIQUE,
+  `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network in to which cisco vnmc device is added',
+  `provider_name` varchar(255) NOT NULL COMMENT 'Service Provider name corresponding to this cisco vnmc device',
+  `device_name` varchar(255) NOT NULL COMMENT 'name of the cisco vnmc device',
+  `host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external cisco vnmc device',
+  PRIMARY KEY (`id`),
+  CONSTRAINT `fk_external_cisco_vnmc_devices__host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE,
+  CONSTRAINT `fk_external_cisco_vnmc_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+CREATE TABLE `cloud`.`external_cisco_asa1000v_devices` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
+  `uuid` varchar(255) UNIQUE,
+  `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network in to which cisco asa1kv device is added',
+  `management_ip` varchar(255) UNIQUE NOT NULL COMMENT 'mgmt. ip of cisco asa1kv device',
+  `in_port_profile` varchar(255) NOT NULL COMMENT 'inside port profile name of cisco asa1kv device',
+  `cluster_id` bigint unsigned NOT NULL COMMENT 'id of the Vmware cluster to which cisco asa1kv device is attached (cisco n1kv switch)',
+  PRIMARY KEY (`id`),
+  CONSTRAINT `fk_external_cisco_asa1000v_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE,
+  CONSTRAINT `fk_external_cisco_asa1000v_devices__cluster_id` FOREIGN KEY (`cluster_id`) REFERENCES `cluster`(`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+CREATE TABLE `cloud`.`network_asa1000v_map` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
+  `network_id` bigint unsigned NOT NULL UNIQUE COMMENT 'id of guest network',
+  `asa1000v_id` bigint unsigned NOT NULL UNIQUE COMMENT 'id of asa1000v device',
+  PRIMARY KEY (`id`),
+  CONSTRAINT `fk_network_asa1000v_map__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`) ON DELETE CASCADE,
+  CONSTRAINT `fk_network_asa1000v_map__asa1000v_id` FOREIGN KEY (`asa1000v_id`) REFERENCES `external_cisco_asa1000v_devices`(`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
 -- Re-enable foreign key checking, at the end of the upgrade path
 SET foreign_key_checks = 1;			
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/test/integration/component/test_asa1000v_fw.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_asa1000v_fw.py b/test/integration/component/test_asa1000v_fw.py
new file mode 100755
index 0000000..0b66f97
--- /dev/null
+++ b/test/integration/component/test_asa1000v_fw.py
@@ -0,0 +1,134 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+""" Cisco ASA1000v external firewall
+"""
+#Import Local Modules
+import marvin
+from nose.plugins.attrib import attr
+from marvin.cloudstackTestCase import *
+from marvin.cloudstackAPI import *
+from marvin.integration.lib.utils import *
+from marvin.integration.lib.base import *
+from marvin.integration.lib.common import *
+from marvin.remoteSSHClient import remoteSSHClient
+import datetime
+
+
+class Services:
+    """Test Cisco ASA1000v services
+    """
+
+    def __init__(self):
+        self.services = {
+                        "vnmc": {
+                                    "ipaddress": '10.147.28.236',
+                                    "username": 'admin',
+                                    "password": 'Password_123',
+                        },
+                        "asa": {
+                                    "ipaddress": '10.147.28.238',
+                                    "insideportprofile": 'asa-in123',
+                        },
+                        "network_offering": {
+                                    "name": 'CiscoVnmc',
+                                    "displaytext": 'CiscoVnmc',
+                                    "guestiptype": 'Isolated',
+                                    "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Firewall,UserData,StaticNat',
+                                    "traffictype": 'GUEST',
+                                    "availability": 'Optional',
+                                    "serviceProviderList": {
+                                            "Dhcp": 'VirtualRouter',
+                                            "Dns": 'VirtualRouter',
+                                            "SourceNat": 'CiscoVnmc',
+                                            "PortForwarding": 'CiscoVnmc',
+                                            "Firewall": 'CiscoVnmc',
+                                            "UserData": 'VirtualRouter',
+                                            "StaticNat": 'CiscoVnmc',
+                                    },
+                        },
+                        "network": {
+                                    "name": "CiscoVnmc",
+                                    "displaytext": "CiscoVnmc",
+                        },
+                    }
+
+class TestASASetup(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        cls.apiclient = super(
+                            TestASASetup,
+                            cls
+                            ).getClsTestClient().getApiClient()
+        cls.services = Services().services
+        cls.network_offering = NetworkOffering.create(
+                            cls.apiclient,
+                            cls.services["network_offering"],
+                            conservemode=True)
+        # Enable network offering
+        cls.network_offering.update(cls.apiclient, state='Enabled')
+
+        cls._cleanup = [
+                        cls.network_offering,
+                      ]
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            # Cleanup
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.dbclient = self.testClient.getDbConnection()
+
+        self.zone = get_zone(self.apiclient, self.services)
+        self.physicalnetworks = PhysicalNetwork.list(self.apiclient, zoneid=self.zone.id)
+        self.assertNotEqual(len(self.physicalnetworks), 0, "Check if the list physical network API returns a non-empty response")
+        self.clusters = Cluster.list(self.apiclient, hypervisor='VMware')
+        self.assertNotEqual(len(self.clusters), 0, "Check if the list cluster API returns a non-empty response")
+
+        return
+
+    def tearDown(self):
+        try:
+            self.debug("Cleaning up the resources")
+            # Cleanup
+            cleanup_resources(self.apiclient, self._cleanup)
+            self.debug("Cleanup complete!")
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    def test_registerVnmc(self):
+        Vnmc = VNMC.create(self.apiclient, self.services["vnmc"]["ipaddress"], self.services["vnmc"]["username"], self.services["vnmc"]["password"], self.physicalnetworks[0].id)
+        self.debug("Cisco VNMC appliance with id %s deployed"%(Vnmc.id))
+        VnmcList = VNMC.list(self.apiclient, physicalnetworkid = self.physicalnetworks[0].id)
+        self.assertNotEqual(len(VnmcList), 0, "List VNMC API returned an empty response")
+        Vnmc.delete(self.apiclient)
+
+    def test_registerAsa1000v(self):
+        Asa = ASA1000V.create(self.apiclient, self.services["asa"]["ipaddress"], self.services["asa"]["insideportprofile"], self.clusters[0].id, self.physicalnetworks[0].id)
+        self.debug("Cisco ASA 1000v appliance with id %s deployed"%(Asa.id))
+        AsaList = ASA1000V.list(self.apiclient, physicalnetworkid = self.physicalnetworks[0].id)
+        self.assertNotEqual(len(AsaList), 0, "List ASA 1000v API returned an empty response")
+        Asa.delete(self.apiclient)
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/tools/marvin/marvin/integration/lib/base.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py
index 3df68ab..0185c87 100755
--- a/tools/marvin/marvin/integration/lib/base.py
+++ b/tools/marvin/marvin/integration/lib/base.py
@@ -2444,7 +2444,6 @@ class VPC:
         [setattr(cmd, k, v) for k, v in kwargs.items()]
         return(apiclient.listVPCs(cmd))
 
-
 class AffinityGroup:
     def __init__(self, items):
         self.__dict__.update(items)
@@ -2467,9 +2466,71 @@ class AffinityGroup:
         cmd.id = self.id
         return apiclient.deleteVPC(cmd)
 
-
     @classmethod
     def list(cls, apiclient, **kwargs):
         cmd = listAffinityGroups.listAffinityGroupsCmd()
         [setattr(cmd, k, v) for k, v in kwargs.items()]
         return(apiclient.listVPCs(cmd))
+
+class VNMC:
+    """Manage VNMC lifecycle"""
+
+    def __init__(self, items):
+        self.__dict__.update(items)
+
+    def create(cls, apiclient, hostname, username, password, physicalnetworkid):
+        """Registers VNMC appliance"""
+
+        cmd = addCiscoVnmcResource.addCiscoVnmcResourceCmd()
+        cmd.hostname = hostname
+        cmd.username = username
+        cmd.password = password
+        cmd.physicalnetworkid = physicalnetworkid
+        return VNMC(apiclient.addCiscoVnmcResource(cmd))
+
+    def delete(self, apiclient):
+        """Removes VNMC appliance"""
+
+        cmd = deleteCiscoVnmcResource.deleteCiscoVnmcResourceCmd()
+        cmd.resourceid = self.resourceid
+        return apiclient.deleteCiscoVnmcResource(cmd)
+
+    @classmethod
+    def list(cls, apiclient, **kwargs):
+        """List VNMC appliances"""
+
+        cmd = listCiscoVnmcResources.listCiscoVnmcResourcesCmd()
+        [setattr(cmd, k, v) for k, v in kwargs.items()]
+        return(apiclient.listCiscoVnmcResources(cmd))
+
+class ASA1000V:
+    """Manage ASA 1000v lifecycle"""
+
+    def __init__(self, items):
+        self.__dict__.update(items)
+
+    @classmethod
+    def create(cls, apiclient, hostname, insideportprofile, clusterid, physicalnetworkid):
+        """Registers ASA 1000v appliance"""
+
+        cmd = addCiscoAsa1000vResource.addCiscoAsa1000vResourceCmd()
+        cmd.hostname = hostname
+        cmd.insideportprofile = insideportprofile
+        cmd.clusterid = clusterid
+        cmd.physicalnetworkid = physicalnetworkid
+        return ASA1000V(apiclient.addCiscoAsa1000vResource(cmd))
+
+    def delete(self, apiclient):
+        """Removes ASA 1000v appliance"""
+
+        cmd = deleteCiscoAsa1000vResource.deleteCiscoAsa1000vResourceCmd()
+        cmd.resourceid = self.resourceid
+        return apiclient.deleteCiscoAsa1000vResource(cmd)
+
+    @classmethod
+    def list(cls, apiclient, **kwargs):
+        """List ASA 1000v appliances"""
+
+        cmd = listCiscoAsa1000vResources.listCiscoAsa1000vResourcesCmd()
+        [setattr(cmd, k, v) for k, v in kwargs.items()]
+        return(apiclient.listCiscoAsa1000vResources(cmd))

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
index be8d68a..06718d0 100644
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
+++ b/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java
@@ -80,6 +80,17 @@ public class NetconfHelper {
     }
 
     public void addPortProfile(String name, PortProfileType type, BindingType binding,
+            SwitchPortMode mode, int vlanid, String vdc, String espName) throws CloudRuntimeException {
+        String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid, vdc, espName);
+        if (command != null) {
+            command = command.concat(SSH_NETCONF_TERMINATOR);
+            parseOkReply(sendAndReceive(command));
+        } else {
+            throw new CloudRuntimeException("Error generating rpc request for adding port profile.");
+        }
+    }
+
+    public void addPortProfile(String name, PortProfileType type, BindingType binding,
             SwitchPortMode mode, int vlanid) throws CloudRuntimeException {
         String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid);
         if (command != null) {
@@ -160,6 +171,17 @@ public class NetconfHelper {
         }
     }
 
+    public void addVServiceNode(String vlanId, String ipAddr)
+            throws CloudRuntimeException {
+        String command = VsmCommand.getVServiceNode(vlanId, ipAddr);
+        if (command != null) {
+            command = command.concat(SSH_NETCONF_TERMINATOR);
+            parseOkReply(sendAndReceive(command));
+        } else {
+            throw new CloudRuntimeException("Error generating rpc request for adding vservice node for vlan " + vlanId);
+        }
+    }
+
     public PortProfile getPortProfileByName(String name) throws CloudRuntimeException {
         String command = VsmCommand.getPortProfile(name);
         if (command != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e94c7025/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
index d1887f6..fdab390 100644
--- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
+++ b/utils/src/com/cloud/utils/cisco/n1kv/vsm/VsmCommand.java
@@ -70,6 +70,40 @@ public class VsmCommand {
     }
 
     public static String getAddPortProfile(String name, PortProfileType type,
+            BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) {
+        try {
+            // Create the document and root element.
+            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+            DOMImplementation domImpl = docBuilder.getDOMImplementation();
+            Document doc = createDocument(domImpl);
+
+            // Edit configuration command.
+            Element editConfig = doc.createElement("nf:edit-config");
+            doc.getDocumentElement().appendChild(editConfig);
+
+            // Command to get into exec configure mode.
+            Element target = doc.createElement("nf:target");
+            Element running = doc.createElement("nf:running");
+            target.appendChild(running);
+            editConfig.appendChild(target);
+
+            // Command to create the port profile with the desired configuration.
+            Element config = doc.createElement("nf:config");
+            config.appendChild(configPortProfileDetails(doc, name, type, binding, mode, vlanid, vdc, espName));
+            editConfig.appendChild(config);
+
+            return serialize(domImpl, doc);
+        } catch (ParserConfigurationException e) {
+            s_logger.error("Error while creating add port profile message : " + e.getMessage());
+            return null;
+        } catch (DOMException e) {
+            s_logger.error("Error while creating add port profile message : " + e.getMessage());
+            return null;
+        }
+    }
+
+    public static String getAddPortProfile(String name, PortProfileType type,
             BindingType binding, SwitchPortMode mode, int vlanid) {
         try {
             // Create the document and root element.
@@ -366,6 +400,184 @@ public class VsmCommand {
         }
     }
 
+    public static String getVServiceNode(String vlanId, String ipAddr) {
+        try {
+            // Create the document and root element.
+            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+            DOMImplementation domImpl = docBuilder.getDOMImplementation();
+            Document doc = createDocument(domImpl);
+
+            // Edit configuration command.
+            Element editConfig = doc.createElement("nf:edit-config");
+            doc.getDocumentElement().appendChild(editConfig);
+
+            // Command to get into exec configure mode.
+            Element target = doc.createElement("nf:target");
+            Element running = doc.createElement("nf:running");
+            target.appendChild(running);
+            editConfig.appendChild(target);
+
+            // Command to create the port profile with the desired configuration.
+            Element config = doc.createElement("nf:config");
+            config.appendChild(configVServiceNodeDetails(doc, vlanId, ipAddr));
+            editConfig.appendChild(config);
+
+            return serialize(domImpl, doc);
+        } catch (ParserConfigurationException e) {
+            s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
+            return null;
+        } catch (DOMException e) {
+            s_logger.error("Error while adding vservice node for vlan " + vlanId + ", " + e.getMessage());
+            return null;
+        }
+    }
+
+    private static Element configVServiceNodeDetails(Document doc, String vlanId, String ipAddr) {
+        // In mode, exec_configure.
+        Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+        Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+        configure.appendChild(modeConfigure);
+
+        // vservice node %name% type asa
+        Element vservice = doc.createElement("vservice");
+        vservice.appendChild(doc.createElement("node"))
+                .appendChild(doc.createElement("ASA_" + vlanId))
+                .appendChild(doc.createElement("type"))
+                .appendChild(doc.createElement("asa"));
+        modeConfigure.appendChild(vservice);
+
+        Element address = doc.createElement(s_paramvalue);
+        address.setAttribute("isKey", "true");
+        address.setTextContent(ipAddr);
+
+        // ip address %ipAddr%
+        modeConfigure.appendChild(doc.createElement("ip"))
+        		.appendChild(doc.createElement("address"))
+                .appendChild(doc.createElement("value"))
+        		.appendChild(address);
+
+        Element vlan = doc.createElement(s_paramvalue);
+        vlan.setAttribute("isKey", "true");
+        vlan.setTextContent(vlanId);
+
+        // adjacency l2 vlan %vlanId%
+        modeConfigure.appendChild(doc.createElement("adjacency"))
+                .appendChild(doc.createElement("l2"))
+                .appendChild(doc.createElement("vlan"))
+                .appendChild(doc.createElement("value"))
+                .appendChild(vlan);
+
+        // fail-mode close
+        modeConfigure.appendChild(doc.createElement("fail-mode"))
+                .appendChild(doc.createElement("close"));
+
+        // Persist the configuration across reboots.
+        modeConfigure.appendChild(persistConfiguration(doc));
+
+        return configure;
+    }
+
+    private static Element configPortProfileDetails(Document doc, String name, PortProfileType type,
+            BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) {
+
+        // In mode, exec_configure.
+        Element configure = doc.createElementNS(s_ciscons, "nxos:configure");
+        Element modeConfigure = doc.createElement("nxos:" + s_configuremode);
+        configure.appendChild(modeConfigure);
+
+        // Port profile name and type configuration.
+        Element portProfile = doc.createElement("port-profile");
+        modeConfigure.appendChild(portProfile);
+
+        // Port profile type.
+        Element portDetails = doc.createElement("name");
+        switch (type) {
+        case none:
+            portProfile.appendChild(portDetails);
+            break;
+        case ethernet:
+            {
+                Element typetag = doc.createElement("type");
+                Element ethernettype = doc.createElement("ethernet");
+                portProfile.appendChild(typetag);
+                typetag.appendChild(ethernettype);
+                ethernettype.appendChild(portDetails);
+            }
+            break;
+        case vethernet:
+            {
+                Element typetag = doc.createElement("type");
+                Element ethernettype = doc.createElement("vethernet");
+                portProfile.appendChild(typetag);
+                typetag.appendChild(ethernettype);
+                ethernettype.appendChild(portDetails);
+            }
+            break;
+        }
+
+        // Port profile name.
+        Element value = doc.createElement(s_paramvalue);
+        value.setAttribute("isKey", "true");
+        value.setTextContent(name);
+        portDetails.appendChild(value);
+
+        // element for port prof mode.
+        Element portProf = doc.createElement(s_portprofmode);
+        portDetails.appendChild(portProf);
+
+        // Binding type.
+        if (binding != BindingType.none) {
+            portProf.appendChild(getBindingType(doc, binding));
+        }
+
+        if (mode != SwitchPortMode.none) {
+            // Switchport mode.
+            portProf.appendChild(getSwitchPortMode(doc, mode));
+            // Adding vlan details.
+            if (vlanid > 0) {
+                portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));
+            }
+        }
+
+        // Command "vmware port-group".
+        Element vmware = doc.createElement("vmware");
+        Element portgroup = doc.createElement("port-group");
+        vmware.appendChild(portgroup);
+        portProf.appendChild(vmware);
+
+        // org root/%vdc%
+        // vservice node <Node Name> profile <Edge Security Profile Name in VNMC>
+        Element org = doc.createElement("org");
+        org.appendChild(doc.createElement(vdc));
+        portProf.appendChild(org);
+
+        String asaNodeName = "ASA_" + vlanid;
+        Element vservice = doc.createElement("vservice");
+        vservice.appendChild(doc.createElement("node"))
+                .appendChild(doc.createElement(asaNodeName))
+                .appendChild(doc.createElement("profile"))
+                .appendChild(doc.createElement(espName));
+        portProf.appendChild(vservice);
+
+        // no shutdown.
+        Element no = doc.createElement("no");
+        Element shutdown = doc.createElement("shutdown");
+        no.appendChild(shutdown);
+        portProf.appendChild(no);
+
+        // Enable the port profile.
+        Element state = doc.createElement("state");
+        Element enabled = doc.createElement("enabled");
+        state.appendChild(enabled);
+        portProf.appendChild(state);
+
+        // Persist the configuration across reboots.
+        modeConfigure.appendChild(persistConfiguration(doc));
+
+        return configure;
+    }
+    
     private static Element configPortProfileDetails(Document doc, String name, PortProfileType type,
             BindingType binding, SwitchPortMode mode, int vlanid) {
 
@@ -433,6 +645,7 @@ public class VsmCommand {
         Element portgroup = doc.createElement("port-group");
         vmware.appendChild(portgroup);
         portProf.appendChild(vmware);
+        
 
         // no shutdown.
         Element no = doc.createElement("no");


Mime
View raw message