Southbound plugin to the OpenContrail Platform - Codebase for M4 release 59/9659/1
authorpchopra <pchopra@juniper.net>
Mon, 4 Aug 2014 15:16:18 +0000 (20:46 +0530)
committerpchopra <pchopra@juniper.net>
Mon, 4 Aug 2014 15:17:22 +0000 (20:47 +0530)
Signed-off-by: pchopra <pchopra@juniper.net>
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/Activator.java
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandler.java [new file with mode: 0755]
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/NetworkHandler.java
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/PortHandler.java
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/RouterHandler.java [new file with mode: 0644]
neutron/src/main/java/org/opendaylight/plugin2oc/neutron/SubnetHandler.java
neutron/src/test/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandlerTest.java [new file with mode: 0755]
neutron/src/test/java/org/opendaylight/plugin2oc/neutron/NetworkHandlerTest.java
neutron/src/test/java/org/opendaylight/plugin2oc/neutron/RouterHandlerTest.java [new file with mode: 0755]
neutron/src/test/java/org/opendaylight/plugin2oc/neutron/SubnetHandlerTest.java

index 5ca486bfaf36d3ab62ed17796d92b860ca52616a..f59c3b5889c6eb236901cc4a399b25b5efecbd56 100755 (executable)
@@ -12,8 +12,10 @@ import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.ApiConnectorFactory;
 
 import org.apache.felix.dm.Component;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFloatingIPAware;
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkAware;
 import org.opendaylight.controller.networkconfig.neutron.INeutronPortAware;
+import org.opendaylight.controller.networkconfig.neutron.INeutronRouterAware;
 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetAware;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
 import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase;
@@ -39,9 +41,9 @@ public class Activator extends ComponentActivatorAbstractBase {
 
     /**
      * Function called to get APIConnector object. porperties must be defined in
-     * opendaylight configuration folder inside config.ini at
-     * opendaylight/distribution
+     * opendaylight configuration folder inside config.ini at opendaylight/distribution
      * /opendaylight/src/main/resources/configuration/config.ini
+     *
      */
     public ApiConnector getApiConnection() {
         String ipAddress = System.getProperty("plugin2oc.apiserver.ipaddress");
@@ -75,7 +77,7 @@ public class Activator extends ComponentActivatorAbstractBase {
      */
     @Override
     public Object[] getImplementations() {
-        Object[] res = { NetworkHandler.class, SubnetHandler.class, PortHandler.class };
+        Object[] res = { NetworkHandler.class, SubnetHandler.class, PortHandler.class, RouterHandler.class, FloatingIpHandler.class };
         return res;
     }
 
@@ -105,6 +107,12 @@ public class Activator extends ComponentActivatorAbstractBase {
         if (imp.equals(PortHandler.class)) {
             c.setInterface(INeutronPortAware.class.getName(), null);
         }
+        if (imp.equals(RouterHandler.class)) {
+            c.setInterface(INeutronRouterAware.class.getName(), null);
+        }
+        if (imp.equals(FloatingIpHandler.class)) {
+            c.setInterface(INeutronFloatingIPAware.class.getName(), null);
+        }
         // Create service dependencies.
         c.add(createServiceDependency().setService(BindingAwareBroker.class).setCallbacks("setBindingAwareBroker", "unsetBindingAwareBroker")
                 .setRequired(true));
diff --git a/neutron/src/main/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandler.java b/neutron/src/main/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandler.java
new file mode 100755 (executable)
index 0000000..1b74543
--- /dev/null
@@ -0,0 +1,360 @@
+/*
+ * Copyright (C) 2014 Juniper Networks, Inc.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ *
+ */
+package org.opendaylight.plugin2oc.neutron;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.util.UUID;
+
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.types.FloatingIp;
+import net.juniper.contrail.api.types.FloatingIpPool;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.types.VirtualMachineInterface;
+import net.juniper.contrail.api.types.VirtualNetwork;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronFloatingIPAware;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFloatingIP;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Handle requests for Neutron Floating IP.
+ */
+public class FloatingIpHandler implements INeutronFloatingIPAware {
+    /**
+     * Logger instance.
+     */
+    static final Logger LOGGER = LoggerFactory.getLogger(PortHandler.class);
+    static ApiConnector apiConnector;
+
+    /**
+     * Invoked when a floating ip creation is requested to check if the
+     * specified floating ip can be created.
+     *
+     * @param floatingip
+     *            An instance of proposed new Neutron Floating ip object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    @Override
+    public int canCreateFloatingIP(NeutronFloatingIP fip) {
+        apiConnector = Activator.apiConnector;
+        if (fip == null) {
+            LOGGER.error("Neutron Floating Ip can not be null ");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (("").equals(fip.getFloatingIPUUID())) {
+            LOGGER.error("Floating Ip UUID can not be null ");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (fip.getTenantUUID() == null || ("").equals(fip.getTenantUUID())) {
+            LOGGER.error("Floating Ip tenant Id can not be null");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (fip.getFloatingIPAddress() == null) {
+            LOGGER.error(" Floating Ip address can not be null");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        try {
+            return createfloatingIp(fip);
+        } catch (Exception e) {
+            e.printStackTrace();
+            LOGGER.error("Exception :   " + e);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked when a floating ip creation is requested to create the floating
+     * ip
+     *
+     * @param floatingip
+     *            An instance of proposed new Neutron Floating ip object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    private int createfloatingIp(NeutronFloatingIP neutronFloatingIp) throws IOException {
+        String projectUUID = null;
+        String floatingPoolNetworkId = null;
+        String fipId = neutronFloatingIp.getID();
+        String floatingIpaddress = neutronFloatingIp.getFloatingIPAddress();
+        try {
+            floatingPoolNetworkId = neutronFloatingIp.getFloatingNetworkUUID();
+            projectUUID = neutronFloatingIp.getTenantUUID().toString();
+            if (!(projectUUID.contains("-"))) {
+                projectUUID = uuidFormater(projectUUID);
+            }
+            projectUUID = UUID.fromString(projectUUID).toString();
+        } catch (Exception ex) {
+            LOGGER.error("UUID input incorrect", ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+        Project project;
+        try {
+            project = (Project) apiConnector.findById(Project.class, projectUUID);
+            if (project == null) {
+                try {
+                    Thread.currentThread();
+                    Thread.sleep(3000);
+                } catch (InterruptedException interruptedException) {
+                    LOGGER.error("InterruptedException :    ", interruptedException);
+                    return HttpURLConnection.HTTP_INTERNAL_ERROR;
+                }
+                project = (Project) apiConnector.findById(Project.class, projectUUID);
+                if (project == null) {
+                    LOGGER.error("Could not find projectUUID...");
+                    return HttpURLConnection.HTTP_NOT_FOUND;
+                }
+            }
+            VirtualNetwork virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, floatingPoolNetworkId);
+            if (virtualNetwork == null) {
+                LOGGER.error("Could not find Virtual network...");
+                return HttpURLConnection.HTTP_NOT_FOUND;
+            }
+            String floatingPoolId = virtualNetwork.getFloatingIpPools().get(0).getUuid();
+            FloatingIpPool floatingIpPool = (FloatingIpPool) apiConnector.findById(FloatingIpPool.class, floatingPoolId);
+            if (floatingIpPool == null) {
+                LOGGER.error("Could not find Floating ip pool...");
+                return HttpURLConnection.HTTP_NOT_FOUND;
+            }
+            FloatingIp floatingIp = new FloatingIp();
+            floatingIp.setUuid(fipId);
+            floatingIp.setName(fipId);
+            floatingIp.setDisplayName(fipId);
+            floatingIp.setAddress(floatingIpaddress);
+            floatingIp.setParent(floatingIpPool);
+            floatingIp.setProject(project);
+            if (neutronFloatingIp.getPortUUID() != null) {
+                VirtualMachineInterface virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class,
+                        neutronFloatingIp.getPortUUID());
+                if (virtualMachineInterface != null) {
+                    floatingIp.addVirtualMachineInterface(virtualMachineInterface);
+                }
+            }
+            boolean floatingIpCreaterd = apiConnector.create(floatingIp);
+            if (!floatingIpCreaterd) {
+                LOGGER.warn("Floating Ip creation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            LOGGER.info("Floating Ip : " + floatingIp.getName() + "  having UUID : " + floatingIp.getUuid() + "  sucessfully created...");
+            return HttpURLConnection.HTTP_OK;
+        } catch (IOException ioEx) {
+            LOGGER.error("Exception : " + ioEx);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a floating ip has been created.
+     *
+     * @param floatingip
+     *            An instance of proposed new Neutron Floating ip object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    @Override
+    public void neutronFloatingIPCreated(NeutronFloatingIP neutronFloatingIp) {
+        FloatingIp floatingIp = null;
+        try {
+            floatingIp = (FloatingIp) apiConnector.findById(FloatingIp.class, neutronFloatingIp.getFloatingIPUUID());
+            if (floatingIp != null) {
+                LOGGER.info("Floating Ip creation verified....");
+            }
+        } catch (Exception ex) {
+            LOGGER.error("Exception :    " + ex);
+        }
+
+    }
+
+    /**
+     * Invoked when a floating ip update is requested to indicate if the
+     * specified floating ip can be changed using the specified delta.
+     *
+     * @param delta
+     *            Updates to the floating ip object using patch semantics.
+     * @param original
+     *            An instance of the Neutron floating ip object to be updated.
+     * @return A HTTP status code to the update request.
+     */
+    @Override
+    public int canUpdateFloatingIP(NeutronFloatingIP deltaFloatingIp, NeutronFloatingIP originalFloatingIp) {
+        apiConnector = Activator.apiConnector;
+        FloatingIp floatingIP = null;
+        apiConnector = Activator.apiConnector;
+        if (deltaFloatingIp == null || originalFloatingIp == null) {
+            LOGGER.error("Neutron Floating Ip can't be null..");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        try {
+            floatingIP = (FloatingIp) apiConnector.findById(FloatingIp.class, originalFloatingIp.getFloatingIPUUID());
+        } catch (IOException e) {
+            LOGGER.error("Exception :     " + e);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+        if (floatingIP == null) {
+            LOGGER.error("No network exists for the specified UUID...");
+            return HttpURLConnection.HTTP_FORBIDDEN;
+        }
+        try {
+            return updateFloatingIP(originalFloatingIp.getFloatingIPUUID(), deltaFloatingIp);
+        } catch (IOException ex) {
+            LOGGER.error("Exception : " + ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+
+    }
+
+    /**
+     * Invoked to update the floating ip
+     *
+     * @param string
+     *            An instance of floating ip UUID.
+     * @param delta_floatingip
+     *            An instance of delta floating ip.
+     *
+     * @return A boolean to the update request.
+     * @throws IOException
+     */
+    private int updateFloatingIP(String floatingIpUUID, NeutronFloatingIP deltaFloatingIp) throws IOException {
+        FloatingIp floatingIP = (FloatingIp) apiConnector.findById(FloatingIp.class, floatingIpUUID);
+        String virtualMachineInterfaceUUID = deltaFloatingIp.getPortUUID();
+        if (deltaFloatingIp.getPortUUID() != null) {
+            VirtualMachineInterface virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class,
+                    virtualMachineInterfaceUUID);
+            if (virtualMachineInterface != null) {
+                floatingIP.setVirtualMachineInterface(virtualMachineInterface);
+            }
+        }
+        if (virtualMachineInterfaceUUID == null) {
+            floatingIP.clearVirtualMachineInterface();
+        }
+        boolean floatingIpUpdate = apiConnector.update(floatingIP);
+        if (!floatingIpUpdate) {
+            LOGGER.warn("Floating Ip Updation failed..");
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+        LOGGER.info("Floating Ip  having UUID : " + floatingIP.getUuid() + "  has been sucessfully updated...");
+        return HttpURLConnection.HTTP_OK;
+    }
+
+    /**
+     * Invoked to take action after a floating ip has been updated.
+     *
+     * @param floatingIp
+     *            An instance of modified Neutron floating ip object.
+     */
+    @Override
+    public void neutronFloatingIPUpdated(NeutronFloatingIP neutronFloatingIp) {
+        try {
+            FloatingIp floatingIp = (FloatingIp) apiConnector.findById(FloatingIp.class, neutronFloatingIp.getFloatingIPUUID());
+            if (neutronFloatingIp.getPortUUID() != null) {
+                if (floatingIp.getVirtualMachineInterface().get(0).getUuid().matches(neutronFloatingIp.getPortUUID())) {
+                    LOGGER.info("Floating Ip with floating UUID " + neutronFloatingIp.getFloatingIPUUID() + " is Updated successfully.");
+                } else {
+                    LOGGER.info("Floating Ip Updation failed..");
+                }
+            } else if (neutronFloatingIp.getPortUUID() == null && floatingIp.getVirtualMachineInterface() == null) {
+                LOGGER.info("Floating Ip with floating UUID " + neutronFloatingIp.getFloatingIPUUID() + " is Updated successfully.");
+            } else {
+                LOGGER.info("Floating Ip Updation failed..");
+            }
+        } catch (Exception e) {
+            LOGGER.error("Exception :" + e);
+        }
+    }
+
+    /**
+     * Invoked when a floating IP deletion is requested to indicate if the
+     * specified floating IP can be deleted.
+     *
+     * @param NeutronFloatingIP
+     *            An instance of the Neutron {@link FloatingIp} object to be
+     *            deleted.
+     * @return A HTTP status code to the deletion request.
+     */
+    @Override
+    public int canDeleteFloatingIP(NeutronFloatingIP neutronFloatingIp) {
+        apiConnector = Activator.apiConnector;
+        if (neutronFloatingIp == null) {
+            LOGGER.error("Neutron Floating Ip can not be null.. ");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        try {
+            return deleteFloatingIP(neutronFloatingIp.getFloatingIPUUID());
+        } catch (IOException ioEx) {
+            LOGGER.error("Exception : " + ioEx);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        } catch (Exception ex) {
+            LOGGER.error("Exception : " + ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to delete the specified Neutron floating ip.
+     *
+     * @param String
+     *            An instance of floating ip UUID.
+     *
+     * @return A boolean to the delete request.
+     * @throws IOException
+     */
+    private int deleteFloatingIP(String neutronFloatingIp) throws IOException {
+        FloatingIp floatingIp = (FloatingIp) apiConnector.findById(FloatingIp.class, neutronFloatingIp);
+        if (floatingIp != null) {
+            apiConnector.delete(floatingIp);
+            LOGGER.info("Floating Ip with UUID :  " + floatingIp.getUuid() + "  has been deleted successfully....");
+            return HttpURLConnection.HTTP_OK;
+        } else {
+            LOGGER.info("No Floating Ip exists with UUID :  " + neutronFloatingIp);
+            return HttpURLConnection.HTTP_NOT_FOUND;
+        }
+    }
+
+    /**
+     * Invoked to take action after a floatingIP has been deleted.
+     *
+     * @param NeutronfloatingIP
+     *            An instance of deleted floatingIP Network object.
+     */
+    @Override
+    public void neutronFloatingIPDeleted(NeutronFloatingIP neutronFloatingIp) {
+        FloatingIp fip = null;
+        try {
+            fip = (FloatingIp) apiConnector.findById(FloatingIp.class, neutronFloatingIp.getFloatingIPUUID());
+            if (fip == null) {
+                LOGGER.info("Floating ip deletion verified....");
+            }
+        } catch (Exception e) {
+            LOGGER.error("Exception :   " + e);
+        }
+
+    }
+
+    /**
+     * Invoked to format the UUID if UUID is not in correct format.
+     *
+     * @param String
+     *            An instance of UUID string.
+     *
+     * @return Correctly formated UUID string.
+     */
+    private String uuidFormater(String uuid) {
+        String uuidPattern = null;
+        String id1 = uuid.substring(0, 8);
+        String id2 = uuid.substring(8, 12);
+        String id3 = uuid.substring(12, 16);
+        String id4 = uuid.substring(16, 20);
+        String id5 = uuid.substring(20, 32);
+        uuidPattern = (id1 + "-" + id2 + "-" + id3 + "-" + id4 + "-" + id5);
+        return uuidPattern;
+    }
+
+}
index 4ea54ff77ae5c63ce512b7d753671efedc3331fb..4908653f73b8cb4e111763e8e6db0ba424b53323 100755 (executable)
@@ -13,6 +13,7 @@ import java.net.HttpURLConnection;
 import java.util.UUID;
 
 import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.types.FloatingIpPool;
 import net.juniper.contrail.api.types.Project;
 import net.juniper.contrail.api.types.VirtualNetwork;
 
@@ -58,6 +59,40 @@ public class NetworkHandler implements INeutronNetworkAware {
             return HttpURLConnection.HTTP_BAD_REQUEST;
         }
         try {
+            VirtualNetwork virtualNetwork = null;
+            String networkUUID = null;
+            String projectUUID = null;
+            try {
+                networkUUID = UUID.fromString(network.getNetworkUUID()).toString();
+                projectUUID = network.getTenantID().toString();
+                if (!(projectUUID.contains("-"))) {
+                    projectUUID = uuidFormater(projectUUID);
+                }
+                projectUUID = UUID.fromString(projectUUID).toString();
+            } catch (Exception ex) {
+                LOGGER.error("UUID input incorrect", ex);
+                return HttpURLConnection.HTTP_BAD_REQUEST;
+            }
+            virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, networkUUID);
+            Project project = (Project) apiConnector.findById(Project.class, projectUUID);
+            if (project == null) {
+                try {
+                    Thread.currentThread();
+                    Thread.sleep(3000);
+                } catch (InterruptedException e) {
+                    LOGGER.error("InterruptedException :    ", e);
+                    return HttpURLConnection.HTTP_BAD_REQUEST;
+                }
+                project = (Project) apiConnector.findById(Project.class, projectUUID);
+                if (project == null) {
+                    LOGGER.error("Could not find projectUUID...");
+                    return HttpURLConnection.HTTP_NOT_FOUND;
+                }
+            }
+            if (virtualNetwork != null) {
+                LOGGER.warn("Network already exists..");
+                return HttpURLConnection.HTTP_FORBIDDEN;
+            }
             return createNetwork(network);
         } catch (IOException ie) {
             LOGGER.error("IOException :   " + ie);
@@ -97,52 +132,55 @@ public class NetworkHandler implements INeutronNetworkAware {
      */
     private int createNetwork(NeutronNetwork network) throws IOException {
         VirtualNetwork virtualNetwork = null;
-        String networkUUID = null;
-        String projectUUID = null;
+        Project project;
+        virtualNetwork = new VirtualNetwork();
         try {
-            networkUUID = UUID.fromString(network.getNetworkUUID()).toString();
-            projectUUID = network.getTenantID().toString();
-            if (!(projectUUID.contains("-"))) {
-                projectUUID = uuidFormater(projectUUID);
-            }
-            projectUUID = UUID.fromString(projectUUID).toString();
-            LOGGER.info("projectUUID 2  " + projectUUID);
-        } catch (Exception ex) {
-            LOGGER.error("UUID input incorrect", ex);
-            return HttpURLConnection.HTTP_BAD_REQUEST;
-        }
-        virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, networkUUID);
-        Project project = (Project) apiConnector.findById(Project.class, projectUUID);
-        if (project == null) {
-            try {
-                Thread.currentThread();
-                Thread.sleep(3000);
-            } catch (InterruptedException e) {
-                LOGGER.error("InterruptedException :    ", e);
-            }
-            project = (Project) apiConnector.findById(Project.class, projectUUID);
-            if (project == null) {
-                LOGGER.error("Could not find projectUUID...");
-                return HttpURLConnection.HTTP_NOT_FOUND;
-            }
-        }
-        if (virtualNetwork != null) {
-            LOGGER.warn("Network already exists..");
-            return HttpURLConnection.HTTP_FORBIDDEN;
+            project = (Project) apiConnector.findById(Project.class, network.getTenantID());
+            virtualNetwork.setParent(project);
+        } catch (IOException ioEx) {
+            LOGGER.error("Exception : " + ioEx);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
         }
-        virtualNetwork = new VirtualNetwork();
         // map neutronNetwork to virtualNetwork
         virtualNetwork = mapNetworkProperties(network, virtualNetwork);
-        virtualNetwork.setParent(project);
-        boolean networkCreated = apiConnector.create(virtualNetwork);
-        LOGGER.debug("networkCreated:   " + networkCreated);
-        if (!networkCreated) {
-            LOGGER.warn("Network creation failed..");
+        boolean networkCreated;
+        try {
+            networkCreated = apiConnector.create(virtualNetwork);
+            LOGGER.debug("networkCreated:   " + networkCreated);
+            if (!networkCreated) {
+                LOGGER.warn("Network creation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+        } catch (IOException ioEx) {
+            LOGGER.error("Exception : " + ioEx);
             return HttpURLConnection.HTTP_INTERNAL_ERROR;
         }
         LOGGER.info("Network : " + virtualNetwork.getName() + "  having UUID : " + virtualNetwork.getUuid() + "  sucessfully created...");
+        if (virtualNetwork.getRouterExternal()) {
+            FloatingIpPool floatingIpPool = null;
+            String fipId = UUID.randomUUID().toString();
+            floatingIpPool = new FloatingIpPool();
+            floatingIpPool.setName(fipId);
+            floatingIpPool.setDisplayName(fipId);
+            floatingIpPool.setUuid(fipId);
+            floatingIpPool.setParent(virtualNetwork);
+            boolean createFloatingIpPool;
+            try {
+                createFloatingIpPool = apiConnector.create(floatingIpPool);
+                if (!createFloatingIpPool) {
+                    LOGGER.info("Floating Ip pool creation failed..");
+                    return HttpURLConnection.HTTP_INTERNAL_ERROR;
+                } else {
+                    LOGGER.info("Floating Ip pool created with UUID  : " + floatingIpPool.getUuid());
+                }
+            } catch (IOException ioEx) {
+                LOGGER.error("IOException : " + ioEx);
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+        }
         return HttpURLConnection.HTTP_OK;
-    }
+        }
+
 
     /**
      * Invoked to map the NeutronNetwork object properties to the virtualNetwork
@@ -155,11 +193,21 @@ public class NetworkHandler implements INeutronNetworkAware {
      * @return {@link VirtualNetwork}
      */
     private VirtualNetwork mapNetworkProperties(NeutronNetwork neutronNetwork, VirtualNetwork virtualNetwork) {
+        boolean routerExternal = false;
+        boolean ishared = false;
         String networkUUID = neutronNetwork.getNetworkUUID();
         String networkName = neutronNetwork.getNetworkName();
+        if (neutronNetwork.getRouterExternal() != null) {
+            routerExternal = neutronNetwork.getRouterExternal();
+        }
+        if (neutronNetwork.getShared() != null) {
+            ishared = neutronNetwork.getShared();
+        }
         virtualNetwork.setName(networkName);
         virtualNetwork.setUuid(networkUUID);
         virtualNetwork.setDisplayName(networkName);
+        virtualNetwork.setRouterExternal(routerExternal);
+        virtualNetwork.setIsShared(ishared);
         return virtualNetwork;
     }
 
@@ -175,7 +223,7 @@ public class NetworkHandler implements INeutronNetworkAware {
      */
     @Override
     public int canUpdateNetwork(NeutronNetwork deltaNetwork, NeutronNetwork originalNetwork) {
-        VirtualNetwork virtualnetwork = new VirtualNetwork();
+        VirtualNetwork virtualnetwork;
         apiConnector = Activator.apiConnector;
         if (deltaNetwork == null || originalNetwork == null) {
             LOGGER.error("Neutron Networks can't be null..");
@@ -196,7 +244,7 @@ public class NetworkHandler implements INeutronNetworkAware {
             return HttpURLConnection.HTTP_FORBIDDEN;
         } else {
             try {
-                return updateNetwork(deltaNetwork, virtualnetwork);
+                return updateNetwork(originalNetwork.getNetworkUUID(),deltaNetwork);
             } catch (IOException ie) {
                 LOGGER.error("IOException:     " + ie);
                 return HttpURLConnection.HTTP_INTERNAL_ERROR;
@@ -217,20 +265,78 @@ public class NetworkHandler implements INeutronNetworkAware {
      *
      * @return A HTTP status code to the creation request.
      */
-    private int updateNetwork(NeutronNetwork deltaNetwork, VirtualNetwork virtualNetwork) throws IOException {
+    private int updateNetwork(String networkUUID, NeutronNetwork deltaNetwork) throws IOException {
+        VirtualNetwork originalNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, networkUUID);
+        VirtualNetwork virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, networkUUID);
+
         String networkName = deltaNetwork.getNetworkName();
+        if (deltaNetwork.getShared() != null) {
+            virtualNetwork.setIsShared(deltaNetwork.getShared());
+        }
+        if (deltaNetwork.getRouterExternal() != null) {
+            virtualNetwork.setRouterExternal(deltaNetwork.getRouterExternal());
+        }
         virtualNetwork.setName(networkName);
         virtualNetwork.setDisplayName(networkName);
-        {
-            boolean networkUpdate = apiConnector.update(virtualNetwork);
+        boolean networkUpdate;
+        try {
+            networkUpdate = apiConnector.update(virtualNetwork);
             if (!networkUpdate) {
                 LOGGER.warn("Network Updation failed..");
                 return HttpURLConnection.HTTP_INTERNAL_ERROR;
             }
-            LOGGER.info("Network having UUID : " + virtualNetwork.getUuid() + "  has been sucessfully updated...");
-            return HttpURLConnection.HTTP_OK;
+        } catch (IOException e) {
+            LOGGER.warn("Network Updation failed..");
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+        LOGGER.info("Network having UUID : " + virtualNetwork.getUuid() + "  has been sucessfully updated...");
+        if (deltaNetwork.getRouterExternal() != null) {
+            if (!(originalNetwork.getRouterExternal()) && deltaNetwork.getRouterExternal()) {
+            VirtualNetwork updatedVirtualnetwork;
+            try {
+                updatedVirtualnetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, originalNetwork.getUuid());
+                FloatingIpPool floatingIpPool = null;
+                String fipId = UUID.randomUUID().toString();
+                floatingIpPool = new FloatingIpPool();
+                floatingIpPool.setName(fipId);
+                floatingIpPool.setDisplayName(fipId);
+                floatingIpPool.setUuid(fipId);
+                floatingIpPool.setParent(updatedVirtualnetwork);
+                boolean createFloatingIpPool = apiConnector.create(floatingIpPool);
+                if (!createFloatingIpPool) {
+                    LOGGER.info("Floating Ip pool creation failed..");
+                    return HttpURLConnection.HTTP_INTERNAL_ERROR;
+                } else {
+                    LOGGER.info("Floating Ip pool created with UUID  : " + floatingIpPool.getUuid());
+                }
+            } catch (IOException e) {
+                LOGGER.info("Floating Ip pool creation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+        } else if (originalNetwork.getRouterExternal() && !(deltaNetwork.getRouterExternal())) {
+            String floatingPoolId = virtualNetwork.getFloatingIpPools().get(0).getUuid();
+            FloatingIpPool floatingIpPool;
+            try {
+                floatingIpPool = (FloatingIpPool) apiConnector.findById(FloatingIpPool.class, floatingPoolId);
+                if (floatingIpPool != null) {
+                    apiConnector.delete(floatingIpPool);
+                }
+                floatingIpPool = (FloatingIpPool) apiConnector.findById(FloatingIpPool.class, floatingPoolId);
+                if (floatingIpPool == null) {
+                    LOGGER.info("Floating Ip pool removed after update network..");
+                } else {
+                    LOGGER.info("Floating Ip pool removal failed after update network..");
+                    return HttpURLConnection.HTTP_INTERNAL_ERROR;
+                }
+            } catch (IOException e) {
+                LOGGER.info("Floating Ip pool is failed to removed after update network..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
         }
     }
+    return HttpURLConnection.HTTP_OK;
+}
+
 
     /**
      * Invoked to take action after a network has been updated.
@@ -243,7 +349,7 @@ public class NetworkHandler implements INeutronNetworkAware {
         try {
             VirtualNetwork virtualnetwork = new VirtualNetwork();
             virtualnetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, network.getNetworkUUID());
-            if (network.getNetworkName().equalsIgnoreCase(virtualnetwork.getDisplayName())) {
+            if (network.getNetworkName().equalsIgnoreCase(virtualnetwork.getDisplayName()) && network.getRouterExternal().equals(virtualnetwork.getRouterExternal())) {
                 LOGGER.info("Network updatation verified....");
             } else {
                 LOGGER.info("Network updatation failed....");
@@ -253,6 +359,7 @@ public class NetworkHandler implements INeutronNetworkAware {
         }
     }
 
+
     /**
      * Invoked when a network deletion is requested to indicate if the specified
      * network can be deleted.
@@ -286,6 +393,7 @@ public class NetworkHandler implements INeutronNetworkAware {
         }
     }
 
+
     /**
      * Invoked to take action after a network has been deleted.
      *
@@ -300,6 +408,9 @@ public class NetworkHandler implements INeutronNetworkAware {
             if (virtualNetwork == null) {
                 LOGGER.info("Network deletion verified....");
             }
+            else {
+                LOGGER.info("Network deletion failed....");
+            }
         } catch (Exception e) {
             LOGGER.error("Exception :   " + e);
         }
@@ -323,4 +434,5 @@ public class NetworkHandler implements INeutronNetworkAware {
         uuidPattern = (id1 + "-" + id2 + "-" + id3 + "-" + id4 + "-" + id5);
         return uuidPattern;
     }
+
 }
\ No newline at end of file
index bae5b9a50f4dfdb88bbdf7647b7df8797fca6456..8f1aa670b108f6b568d0121b02428031d3230e14 100755 (executable)
@@ -91,10 +91,11 @@ public class PortHandler implements INeutronPortAware {
     private int createPort(NeutronPort neutronPort) {
         String networkID = neutronPort.getNetworkUUID();
         String portID = neutronPort.getID();
-        String portDesc = neutronPort.getID();
+//        String portDesc = neutronPort.getID();
         String deviceID = neutronPort.getDeviceID();
         String projectID = neutronPort.getTenantID();
         String portMACAddress = neutronPort.getMacAddress();
+        String portName = neutronPort.getName();
         VirtualMachineInterface virtualMachineInterface = null;
         VirtualMachine virtualMachine = null;
         VirtualNetwork virtualNetwork = null;
@@ -129,7 +130,7 @@ public class PortHandler implements INeutronPortAware {
                     LOGGER.debug("virtualMachine:   " + virtualMachine);
                     if (virtualMachine == null) {
                         virtualMachine = new VirtualMachine();
-                        virtualMachine.setName(deviceID);
+                        virtualMachine.setName(deviceID+"--"+portName);
                         virtualMachine.setUuid(deviceID);
                         boolean virtualMachineCreated = apiConnector.create(virtualMachine);
                         LOGGER.debug("virtualMachineCreated: " + virtualMachineCreated);
@@ -163,7 +164,7 @@ public class PortHandler implements INeutronPortAware {
                 } else {
                     virtualMachineInterface = new VirtualMachineInterface();
                     virtualMachineInterface.setUuid(portID);
-                    virtualMachineInterface.setName(portDesc);
+                    virtualMachineInterface.setName(portName);
                     virtualMachineInterface.setParent(project);
                     virtualMachineInterface.setVirtualNetwork(virtualNetwork);
                     macAddressesType.addMacAddress(portMACAddress);
@@ -462,10 +463,13 @@ public class PortHandler implements INeutronPortAware {
                 virtualMachineInterface.setVirtualMachine(virtualMachine);
             }
         }
+        if(deviceID == null){
+            virtualMachineInterface.clearVirtualMachine();
+        }
         if (portName != null) {
             virtualMachineInterface.setDisplayName(portName);
         }
-        if ((deviceID != null && !(("").equals(deviceID))) || portName != null || instanceIpUpdate) {
+        if ((deviceID != null && !(("").equals(deviceID))) || portName != null || instanceIpUpdate ) {
             if ((deviceID != null && !(("").equals(deviceID))) || portName != null) {
                 boolean portUpdate = apiConnector.update(virtualMachineInterface);
                 if (!portUpdate) {
@@ -490,13 +494,12 @@ public class PortHandler implements INeutronPortAware {
     @Override
     public void neutronPortUpdated(NeutronPort neutronPort) {
         try {
-            VirtualMachineInterface virtualMachineInterface;
-            virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, neutronPort.getPortUUID());
-            if (("").equals(neutronPort.getDeviceID())) { // TODO : VM Refs not getting cleared correctly - to be fixed
+            VirtualMachineInterface virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, neutronPort.getPortUUID());
+            if (neutronPort.getDeviceID() == null) { // TODO : VM Refs not getting cleared correctly - to be fixed
                 if (neutronPort.getName().matches(virtualMachineInterface.getDisplayName()) && virtualMachineInterface.getVirtualMachine() == null) {
                     LOGGER.info("Port updatation verified....");
                 }
-            } else if (neutronPort.getName().matches(virtualMachineInterface.getDisplayName())
+            } else if (neutronPort.getDeviceID() != null && neutronPort.getName().matches(virtualMachineInterface.getDisplayName())
                     && neutronPort.getDeviceID().matches(virtualMachineInterface.getVirtualMachine().get(0).getUuid())) {
                 LOGGER.info("Port updatation verified....");
             } else {
diff --git a/neutron/src/main/java/org/opendaylight/plugin2oc/neutron/RouterHandler.java b/neutron/src/main/java/org/opendaylight/plugin2oc/neutron/RouterHandler.java
new file mode 100644 (file)
index 0000000..108c24f
--- /dev/null
@@ -0,0 +1,512 @@
+package org.opendaylight.plugin2oc.neutron;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.util.List;
+import java.util.UUID;
+
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.ApiPropertyBase;
+import net.juniper.contrail.api.ObjectReference;
+import net.juniper.contrail.api.types.LogicalRouter;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.types.VirtualMachineInterface;
+import net.juniper.contrail.api.types.VirtualNetwork;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronRouterAware;
+import org.opendaylight.controller.networkconfig.neutron.NeutronRouter;
+import org.opendaylight.controller.networkconfig.neutron.NeutronRouter_Interface;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Handle requests for Neutron Router.
+ */
+public class RouterHandler implements INeutronRouterAware {
+
+    /**
+     * Logger instance.
+     */
+
+    static final Logger LOGGER = LoggerFactory.getLogger(RouterHandler.class);
+    static ApiConnector apiConnector;
+
+    /**
+     * Invoked when a router creation is requested to check if the specified
+     * router can be created and then creates the router
+     *
+     * @param router
+     *            An instance of proposed new Neutron Router object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    @Override
+    public int canCreateRouter(NeutronRouter router) {
+        apiConnector = Activator.apiConnector;
+        if (router == null) {
+            LOGGER.error("Router object can't be null/empty.");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (router.getRouterUUID() == null || ("").equals(router.getRouterUUID())) {
+            LOGGER.error("Router UUID can't be null/empty.");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (router.getTenantID() == null || ("").equals(router.getTenantID())) {
+            LOGGER.error("Tenant can't be null/empty.");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        if (router.getName() == null || ("").equals(router.getName())) {
+            LOGGER.error("Router name can't be null/empty.");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        String projectUUID = router.getTenantID();
+        if (!(projectUUID.contains("-"))) {
+            projectUUID = uuidFormater(projectUUID);
+        }
+        projectUUID = UUID.fromString(projectUUID).toString();
+        Project project;
+        try {
+            project = (Project) apiConnector.findById(Project.class, projectUUID);
+
+            if (project == null) {
+                Thread.currentThread();
+                Thread.sleep(3000);
+                project = (Project) apiConnector.findById(Project.class, projectUUID);
+                if (project == null) {
+                    LOGGER.error("Could not find projectUUID...");
+                    return HttpURLConnection.HTTP_NOT_FOUND;
+                }
+            }
+            return createRouter(router);
+        } catch (InterruptedException interruptedException) {
+            LOGGER.error("InterruptedException :    ", interruptedException);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        } catch (IOException ie) {
+            LOGGER.error("IOException :   " + ie);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to create the specified Neutron Router.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    private int createRouter(NeutronRouter router) throws IOException {
+        LogicalRouter logicalRouter = new LogicalRouter();
+        logicalRouter = mapRouterProperties(router, logicalRouter);
+        String projectUUID = router.getTenantID();
+        if (!(projectUUID.contains("-"))) {
+            projectUUID = uuidFormater(projectUUID);
+        }
+        projectUUID = UUID.fromString(projectUUID).toString();
+        try {
+            Project project = (Project) apiConnector.findById(Project.class, projectUUID);
+            logicalRouter.setParent(project);
+            if (router.getExternalGatewayInfo() != null) {
+                try {
+                    VirtualNetwork virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, router.getExternalGatewayInfo().getNetworkID());
+                    logicalRouter.setVirtualNetwork(virtualNetwork);
+                } catch (IOException ex) {
+                    LOGGER.error("IOException  :    " + ex);
+                }
+            }
+            boolean routerCreated = apiConnector.create(logicalRouter);
+            if (!routerCreated) {
+                LOGGER.warn("Router creation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            LOGGER.info("Router : " + logicalRouter.getName() + "  having UUID : " + logicalRouter.getUuid() + "  sucessfully created...");
+            return HttpURLConnection.HTTP_OK;
+        } catch (IOException ex) {
+            LOGGER.error("IOException :   " + ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a router has been created.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     */
+    @Override
+    public void neutronRouterCreated(NeutronRouter router) {
+        LogicalRouter logicalRouter = null;
+        try {
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, router.getRouterUUID());
+            if (logicalRouter != null) {
+                LOGGER.info("Router creation verified....");
+            }
+        } catch (Exception e) {
+            LOGGER.error("Exception :    " + e);
+        }
+    }
+
+    /**
+     * Invoked when a router deletion is requested to indicate if the specified
+     * router can be deleted.
+     *
+     * @param router
+     *            An instance of the Neutron Router object to be deleted.
+     *
+     * @return A HTTP status code to the deletion request.
+     */
+    @Override
+    public int canDeleteRouter(NeutronRouter router) {
+        apiConnector = Activator.apiConnector;
+        if (router == null) {
+            LOGGER.info("Router object can't be null...");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        try {
+            return deleteRouter(router.getRouterUUID());
+        } catch (Exception ex) {
+            LOGGER.error("Exception :   ", ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to delete the specified Neutron router.
+     *
+     * @param router
+     *            An instance of new Neutron router object.
+     *
+     * @return A HTTP status code to the deletion request.
+     */
+    private int deleteRouter(String routerUUID) {
+        LogicalRouter logicalRouter = null;
+        try {
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, routerUUID);
+            if (logicalRouter != null) {
+                apiConnector.delete(logicalRouter);
+                LOGGER.info("Router with UUID :  " + routerUUID + "  has been deleted successfully....");
+                return HttpURLConnection.HTTP_OK;
+            } else {
+                LOGGER.info("No Router exists with UUID :  " + routerUUID);
+                return HttpURLConnection.HTTP_BAD_REQUEST;
+            }
+        } catch (IOException ex) {
+            LOGGER.error("Exception :    " + ex);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a Router has been deleted.
+     *
+     * @param router
+     *            An instance of deleted Neutron Router object.
+     */
+    @Override
+    public void neutronRouterDeleted(NeutronRouter router) {
+        LogicalRouter logicalRouter = null;
+        try {
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, router.getRouterUUID());
+            if (logicalRouter != null) {
+                LOGGER.info("Router deletion verified....");
+            }
+        } catch (IOException ex) {
+            LOGGER.error("Exception :    " + ex);
+        }
+
+    }
+
+    /**
+     * Invoked when a router update is requested to indicate if the specified
+     * router can be changed using the specified delta.
+     *
+     * @param delta
+     *            Updates to the router object using patch semantics.
+     * @param router
+     *            An instance of the Neutron router object to be updated.
+     * @return A HTTP status code to the update request.
+     */
+    @Override
+    public int canUpdateRouter(NeutronRouter deltaRouter, NeutronRouter router) {
+        apiConnector = Activator.apiConnector;
+        if (deltaRouter == null || router == null) {
+            LOGGER.error("Neutron Router object can't be null..");
+            return HttpURLConnection.HTTP_BAD_REQUEST;
+        }
+        try {
+            LogicalRouter logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, router.getRouterUUID());
+            if (logicalRouter == null) {
+                LOGGER.warn("Router object not found..");
+                return HttpURLConnection.HTTP_NOT_FOUND;
+            }
+            return updateRouter(logicalRouter, deltaRouter);
+        } catch (IOException ioEx) {
+            LOGGER.error("Exception :    " + ioEx);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to update the router
+     *
+     * @param deltaRouter
+     *            An instance of Router.
+     * @param originalRouter
+     *            An instance of new logicalRouter object.
+     *
+     * @return A HTTP status code to the creation request.
+     */
+    private int updateRouter(LogicalRouter logicalRouter, NeutronRouter deltaRouter) throws IOException {
+        try {
+            String routerName = deltaRouter.getName();
+            logicalRouter.setName(routerName);
+            logicalRouter.setDisplayName(routerName);
+            VirtualNetwork virtualNetwork = null;
+            if (deltaRouter.getExternalGatewayInfo() != null) {
+                try {
+                    virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, deltaRouter.getExternalGatewayInfo().getNetworkID());
+                    logicalRouter.setVirtualNetwork(virtualNetwork);
+                } catch (IOException ex) {
+                    LOGGER.error("IOException  :    " + ex);
+                }
+            } else{
+            logicalRouter.clearVirtualNetwork();
+            }
+            boolean routerUpdate = apiConnector.update(logicalRouter);
+            if (!routerUpdate) {
+                LOGGER.warn("Router Updation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            LOGGER.info("Router having UUID : " + logicalRouter.getUuid() + "  has been sucessfully updated...");
+            return HttpURLConnection.HTTP_OK;
+        } catch (Exception e) {
+            LOGGER.error("Exception :    " + e);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a router has been updated.
+     *
+     * @param router
+     *            An instance of modified Neutron router object.
+     */
+    @Override
+    public void neutronRouterUpdated(NeutronRouter router) {
+        try {
+            LogicalRouter logicalRouter = new LogicalRouter();
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, router.getRouterUUID());
+
+            if (router.getName().equalsIgnoreCase(logicalRouter.getName())) {
+                LOGGER.info("Router updatation verified....");
+            } else {
+                LOGGER.info("Router updatation failed....");
+            }
+
+        } catch (Exception ex) {
+            LOGGER.error("Exception :    " + ex);
+        }
+
+    }
+
+    /**
+     * Invoked to attach interface to the specified Neutron Router.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     *
+     * @param routerInterface
+     *            An instance of NeutronRouter_Interface object to be attached.
+     *
+     * @return A HTTP status code to the attach request.
+     */
+    @Override
+    public int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
+        apiConnector = Activator.apiConnector;
+        String portId = routerInterface.getPortUUID();
+        String routerId = router.getRouterUUID();
+        VirtualMachineInterface virtualMachineInterface = null;
+        LogicalRouter logicalRouter = null;
+        try {
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, routerId);
+            virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, portId);
+            if (virtualMachineInterface != null) {
+                logicalRouter.addVirtualMachineInterface(virtualMachineInterface);
+            }
+//            logicalRouter.setDeviceOwner();  // TODO : Support needs to be added
+            boolean updateVMI = apiConnector.update(virtualMachineInterface);
+            if (!updateVMI) {
+                LOGGER.warn("virtualMachineInterface updation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            boolean interfaceAttached = apiConnector.update(logicalRouter);
+            if (!interfaceAttached) {
+                LOGGER.warn("Interface attachment failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            LOGGER.info("Interface : " + logicalRouter.getName() + "  having UUID : " + logicalRouter.getUuid() + "  sucessfully attached with..."
+                    + logicalRouter.getVirtualMachineInterface());
+            return HttpURLConnection.HTTP_OK;
+        } catch (IOException ioEx) {
+            LOGGER.error("IOException :   " + ioEx);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a router interface has been attached.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     *
+     * @param routerInterface
+     *            An instance of NeutronRouter_Interface object to be attached.
+     */
+    @Override
+    public void neutronRouterInterfaceAttached(NeutronRouter router, NeutronRouter_Interface routerInterface) {
+        String portId = routerInterface.getPortUUID();
+        String routerId = router.getRouterUUID();
+        VirtualMachineInterface virtualMachineInterface = null;
+        try {
+            virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, portId);
+            List<ObjectReference<ApiPropertyBase>> virtualMachineList = virtualMachineInterface.getVirtualMachine();
+            if (virtualMachineList != null) {
+                for (ObjectReference<ApiPropertyBase> ref : virtualMachineList) {
+                    String deviceId = ref.getUuid();
+                    if (deviceId.equals(routerId)) {
+                        LOGGER.info("Interface attachment verified to router...");
+                    }
+                }
+            }
+            // if(virtualMachineInterface.getVirtualMachine()!=null &&
+            // something.getDeviceOwner.equals("network:router_interface")){
+            // LOGGER.info("Interface attachment verified to router..." );
+            // }
+        } catch (Exception ex) {
+            LOGGER.error("Exception :    " + ex);
+        }
+
+    }
+
+    /**
+     * Invoked to detach interface to the specified Neutron Router.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     *
+     * @param routerInterface
+     *            An instance of NeutronRouter_Interface object to be detached.
+     *
+     * @return A HTTP status code to the detach request.
+     */
+    @Override
+    public int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
+        apiConnector = Activator.apiConnector;
+        String portId = routerInterface.getPortUUID();
+        String routerId = router.getRouterUUID();
+        VirtualMachineInterface virtualMachineInterface = null;
+        LogicalRouter logicalRouter = null;
+        try {
+            logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, routerId);
+            List<ObjectReference<ApiPropertyBase>> vmiList = logicalRouter.getVirtualMachineInterface();
+            for (ObjectReference<ApiPropertyBase> vmiRef : vmiList) {
+                if(vmiRef.getUuid().matches(portId)){
+                    vmiList.remove(vmiRef);
+                    break;
+                }
+            }
+            virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, portId);
+//            virtualMachineInterface.clearDeviceId(); //TODO - support to be added in OpenContrail
+            // virtualMachineInterface.clearDeviceId(); //TODO - support to be added in OpenContrail
+            boolean updateVMI = apiConnector.update(virtualMachineInterface);
+            if (!updateVMI) {
+                LOGGER.warn("virtualMachineInterface updation failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            boolean interfaceDetached = apiConnector.update(logicalRouter);
+            if (!interfaceDetached) {
+                LOGGER.warn("Interface detachment failed..");
+                return HttpURLConnection.HTTP_INTERNAL_ERROR;
+            }
+            LOGGER.info("Interface : " + logicalRouter.getName() + "  having UUID : " + logicalRouter.getUuid() + "  sucessfully detached from..."
+                    + logicalRouter.getVirtualMachineInterface());
+            return HttpURLConnection.HTTP_OK;
+        } catch (IOException e) {
+            LOGGER.error("IOException :   " + e);
+            return HttpURLConnection.HTTP_INTERNAL_ERROR;
+        }
+    }
+
+    /**
+     * Invoked to take action after a router interface has been detached.
+     *
+     * @param router
+     *            An instance of new Neutron Router object.
+     *
+     * @param routerInterface
+     *            An instance of NeutronRouter_Interface object to be attached.
+     */
+    @Override
+    public void neutronRouterInterfaceDetached(NeutronRouter router, NeutronRouter_Interface routerInterface) {
+        String routerId = router.getRouterUUID();
+        String portId = routerInterface.getPortUUID();
+        try {
+            VirtualMachineInterface virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, portId);
+            LogicalRouter logicalRouter = (LogicalRouter) apiConnector.findById(LogicalRouter.class, routerId);
+            // if(virtualMachineInterface.getVirtualMachine()==null &&
+            // virtualMachineInterface.getDeviceOwner==null){
+            // LOGGER.info("Interface detachment verified from router..." );
+            // }
+        } catch (Exception e) {
+            LOGGER.error("Exception :    " + e);
+        }
+    }
+
+    /**
+     * Invoked to map the NeutronRouter object properties to the logicalRouter
+     * object.
+     *
+     * @param neutronRouter
+     *            An instance of new Neutron Router object.
+     * @param logicalRouter
+     *            An instance of new logicalRouter object.
+     * @return {@link logicalRouter}
+     */
+    private LogicalRouter mapRouterProperties(NeutronRouter neutronRouter, LogicalRouter logicalRouter) {
+        String routerUUID = neutronRouter.getRouterUUID();
+        String routerName = neutronRouter.getName();
+        logicalRouter.setUuid(routerUUID);
+        logicalRouter.setName(routerName);
+        logicalRouter.setDisplayName(routerName);
+        VirtualNetwork virtualNetwork = null;
+        if (neutronRouter.getExternalGatewayInfo() != null) {
+            try {
+                virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, neutronRouter.getExternalGatewayInfo().getNetworkID());
+                logicalRouter.setVirtualNetwork(virtualNetwork);
+            } catch (IOException ex) {
+                LOGGER.error("IOException  :    " + ex);
+            }
+        }
+        return logicalRouter;
+    }
+
+    /**
+     * Invoked to format the UUID if UUID is not in correct format.
+     *
+     * @param String
+     *            An instance of UUID string.
+     *
+     * @return Correctly formated UUID string.
+     */
+    private String uuidFormater(String uuid) {
+        String uuidPattern = null;
+        String id1 = uuid.substring(0, 8);
+        String id2 = uuid.substring(8, 12);
+        String id3 = uuid.substring(12, 16);
+        String id4 = uuid.substring(16, 20);
+        String id5 = uuid.substring(20, 32);
+        uuidPattern = (id1 + "-" + id2 + "-" + id3 + "-" + id4 + "-" + id5);
+        return uuidPattern;
+    }
+
+}
index 826edd3bf8bf81c2b642e7d10d7fb584cc8d6692..d43b28480579d4015aa55e1e51d5de35083973b8 100755 (executable)
@@ -19,6 +19,8 @@ import net.juniper.contrail.api.types.NetworkIpam;
 import net.juniper.contrail.api.types.SubnetType;
 import net.juniper.contrail.api.types.VirtualNetwork;
 import net.juniper.contrail.api.types.VnSubnetsType;
+import net.juniper.contrail.api.types.VnSubnetsType.IpamSubnetType;
+//import net.juniper.contrail.api.types.VnSubnetsType.IpamSubnetType.AllocationPoolType;
 
 import org.apache.commons.net.util.SubnetUtils;
 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
@@ -150,11 +152,12 @@ public class SubnetHandler implements INeutronSubnetAware {
             LOGGER.warn("Subnet creation failed..");
             return HttpURLConnection.HTTP_INTERNAL_ERROR;
         } else {
-            LOGGER.info("Subnet " + subnet.getCidr() + "sucessfully added to the network having UUID : " + virtualnetwork.getUuid());
+            LOGGER.info("Subnet " + subnet.getCidr() + " sucessfully added to the network having UUID : " + virtualnetwork.getUuid());
             return HttpURLConnection.HTTP_OK;
         }
     }
 
+
     /**
      * Invoked to add the NeutronSubnet properties to the virtualNetwork object.
      *
@@ -187,13 +190,21 @@ public class SubnetHandler implements INeutronSubnetAware {
         if (ipPrefix != null) {
             subnetType.setIpPrefix(ipPrefix[0]);
             subnetType.setIpPrefixLen(Integer.valueOf(ipPrefix[1]));
+//            AllocationPoolType allocationPoolType = (AllocationPoolType) subnet.getAllocationPools();
+            IpamSubnetType ipamSubnetType = new IpamSubnetType();
+            ipamSubnetType.setSubnet(subnetType);
+            ipamSubnetType.setDefaultGateway(subnet.getGatewayIP());
+            ipamSubnetType.setSubnetUuid(subnet.getSubnetUUID());
+            ipamSubnetType.setSubnetName(subnet.getName());
+            ipamSubnetType.setEnableDhcp(subnet.isEnableDHCP());
+//            ipamSubnetType.addAllocationPools(allocationPoolType);
             if (vn.getNetworkIpam() != null) {
                 for (ObjectReference<VnSubnetsType> ref : vn.getNetworkIpam()) {
                     vnSubnetsType = ref.getAttr();
-                    vnSubnetsType.addIpamSubnets(subnetType, subnet.getGatewayIP(), subnet.getSubnetUUID());
+                    vnSubnetsType.addIpamSubnets(ipamSubnetType);
                 }
             } else {
-                vnSubnetsType.addIpamSubnets(subnetType, subnet.getGatewayIP(), subnet.getSubnetUUID());
+                vnSubnetsType.addIpamSubnets(ipamSubnetType);
             }
             vn.setNetworkIpam(ipam, vnSubnetsType);
         }
@@ -236,15 +247,16 @@ public class SubnetHandler implements INeutronSubnetAware {
             LOGGER.error("Neutron Subnets can't be null..");
             return HttpURLConnection.HTTP_BAD_REQUEST;
         }
-        if (deltaSubnet.getGatewayIP() == null || ("").equals(deltaSubnet.getGatewayIP().toString())) {
-            LOGGER.error("Gateway IP can't be empty/null`..");
-            return HttpURLConnection.HTTP_BAD_REQUEST;
-        }
+//        if (deltaSubnet.getGatewayIP() == null || ("").equals(deltaSubnet.getGatewayIP().toString())) {
+//            LOGGER.error("Gateway IP can't be empty/null`..");
+//            return HttpURLConnection.HTTP_BAD_REQUEST;
+//        }
+        if (deltaSubnet.getGatewayIP() != null){
         boolean isvalidGateway = validGatewayIP(originalSubnet, deltaSubnet.getGatewayIP());
         if (!isvalidGateway) {
             LOGGER.error("Incorrect gateway IP....");
             return HttpURLConnection.HTTP_BAD_REQUEST;
-        }
+        }}
         apiConnector = Activator.apiConnector;
         try {
             boolean ifSubnetExist = false;
@@ -258,7 +270,15 @@ public class SubnetHandler implements INeutronSubnetAware {
                         for (VnSubnetsType.IpamSubnetType subnetValue : subnets) {
                             boolean doesSubnetExist = subnetValue.getSubnetUuid().matches(originalSubnet.getSubnetUUID());
                             if (doesSubnetExist) {
+                                if(deltaSubnet.getGatewayIP() != null){
                                 subnetValue.setDefaultGateway(deltaSubnet.getGatewayIP());
+                                }
+                                if(deltaSubnet.getEnableDHCP() != null){
+                                    subnetValue.setEnableDhcp(deltaSubnet.isEnableDHCP());
+                                }
+                                if(deltaSubnet.getName() != null){
+                                    subnetValue.setSubnetName(deltaSubnet.getName());
+                                }
                                 ifSubnetExist = true;
                             }
                         }
@@ -271,7 +291,7 @@ public class SubnetHandler implements INeutronSubnetAware {
                     LOGGER.warn("Subnet upadtion failed..");
                     return HttpURLConnection.HTTP_INTERNAL_ERROR;
                 } else {
-                    LOGGER.info(" Subnet " + originalSubnet.getCidr() + " sucessfully updated with gateway IP : " + deltaSubnet.getGatewayIP());
+                    LOGGER.info(" Subnet " + originalSubnet.getCidr() + " sucessfully updated. ");
                     return HttpURLConnection.HTTP_OK;
                 }
             } else {
diff --git a/neutron/src/test/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandlerTest.java b/neutron/src/test/java/org/opendaylight/plugin2oc/neutron/FloatingIpHandlerTest.java
new file mode 100755 (executable)
index 0000000..3cce802
--- /dev/null
@@ -0,0 +1,205 @@
+package org.opendaylight.plugin2oc.neutron;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.mock;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.types.FloatingIp;
+import net.juniper.contrail.api.types.FloatingIpPool;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.types.VirtualNetwork;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.mockito.Mockito.when;
+
+import org.opendaylight.controller.networkconfig.neutron.NeutronFloatingIP;
+
+public class FloatingIpHandlerTest {
+
+    FloatingIpHandler floatingIphandler;
+    NeutronFloatingIP mockedNeutronFloatingIP = mock(NeutronFloatingIP.class);
+    ApiConnector mockedApiConnector = mock(ApiConnector.class);
+    VirtualNetwork mockedVirtualNetwork = mock(VirtualNetwork.class);
+    FloatingIp mockedFloatingIp = mock(FloatingIp.class);
+    Project mockProject = mock(Project.class);
+    FloatingIpPool mockFloatingIpPool = mock(FloatingIpPool.class);
+
+    @Before
+    public void beforeTest() {
+        floatingIphandler = new FloatingIpHandler();
+        assertNotNull(mockedApiConnector);
+        assertNotNull(mockedNeutronFloatingIP);
+        assertNotNull(mockedVirtualNetwork);
+        assertNotNull(mockProject);
+        assertNotNull(mockFloatingIpPool);
+    }
+
+    @After
+    public void AfterTest() {
+        floatingIphandler = null;
+        Activator.apiConnector = null;
+    }
+
+    /* dummy params for Neutron Floating Ip */
+    public NeutronFloatingIP defaultNeutronObject() {
+        NeutronFloatingIP neutronFloatingIp = new NeutronFloatingIP();
+        neutronFloatingIp.setFixedIPAddress("10.0.0.254");
+        neutronFloatingIp.setFloatingIPAddress("10.0.1.254");
+        neutronFloatingIp.setFloatingIPUUID("6b9570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutronFloatingIp.setFloatingNetworkUUID("54a271fe-0216-46bc-a3e6-1ff582fbd324");
+        neutronFloatingIp.setPortUUID("64a271fe-0216-46bc-a3e6-1ff582fbd324");
+        neutronFloatingIp.setTenantUUID("100071fe-0216-46bc-a3e6-1ff582fbd324");
+        return neutronFloatingIp;
+    }
+
+    /* dummy params for Neutron Floating Ip for update */
+    public NeutronFloatingIP deltaNeutronObjectUpdate() {
+        NeutronFloatingIP neutronFloatingIp = new NeutronFloatingIP();
+        neutronFloatingIp.setFixedIPAddress("10.0.0.254");
+        neutronFloatingIp.setFloatingIPAddress("10.0.1.254");
+        neutronFloatingIp.setFloatingIPUUID("6b9570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutronFloatingIp.setFloatingNetworkUUID("54a271fe-0216-46bc-a3e6-1ff582fbd324");
+        neutronFloatingIp.setPortUUID("64a271fe-0216-46bc-a3e6-1ff582fbd324");
+        neutronFloatingIp.setTenantUUID("100071fe-0216-46bc-a3e6-1ff582fbd324");
+        return neutronFloatingIp;
+    }
+
+    /* dummy params for Neutron Floating Ip Pools */
+    public FloatingIpPool defaultFloatingIpPoolObject() {
+        FloatingIpPool neutronFloatingIpPool = new FloatingIpPool();
+        neutronFloatingIpPool.setDisplayName("name");
+        neutronFloatingIpPool.setName("name");
+        neutronFloatingIpPool.setUuid("6b9570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        return neutronFloatingIpPool;
+    }
+
+    /* Test method to check if neutron floating ip is null */
+    @Test
+    public void testCanCreateFloatingIPNull() {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canCreateFloatingIP(null));
+    }
+
+    /* Test method to check if neutron floating ip UUID is null */
+    @Test
+    public void testCanCreateFloatingIPUuidNull() {
+        Activator.apiConnector = mockedApiConnector;
+        when(mockedNeutronFloatingIP.getFloatingIPUUID()).thenReturn("");
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canCreateFloatingIP(mockedNeutronFloatingIP));
+    }
+
+    /* Test method to check if neutron Tenant UUID is null */
+    @Test
+    public void testCanCreateTenantUUIDNull() {
+        Activator.apiConnector = mockedApiConnector;
+        when(mockedNeutronFloatingIP.getTenantUUID()).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canCreateFloatingIP(mockedNeutronFloatingIP));
+    }
+
+    /* Test method to check if neutron Floating IP Address is null */
+    @Test
+    public void testCanCreateFloatingIPAddressNull() {
+        Activator.apiConnector = mockedApiConnector;
+        when(mockedNeutronFloatingIP.getTenantUUID()).thenReturn("100071fe-0216-46bc-a3e6-1ff582fbd329");
+        when(mockedNeutronFloatingIP.getFloatingIPAddress()).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canCreateFloatingIP(mockedNeutronFloatingIP));
+    }
+
+    /* Test method to check if neutron Floating IP canCreate project is null */
+    @Test
+    public void testCanCreateFloatingProjectNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        when(mockedApiConnector.findById(Project.class, neutronFloatingIP.getTenantUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, floatingIphandler.canCreateFloatingIP(neutronFloatingIP));
+    }
+
+    /* Test method to check if neutron Floating IP canCreate project is null */
+    @Test
+    public void testCanCreateFloatingVirtualNetworkNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        when(mockedApiConnector.findById(Project.class, neutronFloatingIP.getTenantUUID())).thenReturn(mockProject);
+        when(mockedApiConnector.findById(VirtualNetwork.class, neutronFloatingIP.getFloatingNetworkUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, floatingIphandler.canCreateFloatingIP(neutronFloatingIP));
+    }
+
+    // /* Test method to check if neutron Floating IP canCreate project is
+    // null*/
+    // @Test
+    // public void testCanCreateFloatingIpNull() throws IOException {
+    // Activator.apiConnector = mockedApiConnector;
+    // NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+    // when(mockedApiConnector.findById(Project.class,
+    // neutronFloatingIP.getTenantUUID())).thenReturn(mockProject);
+    // when(mockedApiConnector.findById(VirtualNetwork.class,
+    // neutronFloatingIP.getFloatingNetworkUUID())).thenReturn(mockedVirtualNetwork);
+    // when(mockedApiConnector.findById(FloatingIpPool.class,
+    // mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid())).thenReturn(null);
+    // assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
+    // floatingIphandler.canCreateFloatingIP(neutronFloatingIP));
+    // }
+    /* Test method to check if can update FloatingIP Null object */
+    @Test
+    public void testcanUpdateFloatingIPObjNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canUpdateFloatingIP(null, null));
+    }
+
+    /* Test method to check if can update FloatingIP Null */
+    @Test
+    public void testcanUpdateFloatingIPNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        NeutronFloatingIP deltaNeutronFloatingIP = deltaNeutronObjectUpdate();
+        when(mockedApiConnector.findById(FloatingIp.class, neutronFloatingIP.getFloatingIPUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, floatingIphandler.canUpdateFloatingIP(deltaNeutronFloatingIP, neutronFloatingIP));
+    }
+
+    /* Test method to check if can update FloatingIP failed */
+    @Test
+    public void testcanUpdateFloatingIPFailed() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        NeutronFloatingIP deltaNeutronFloatingIP = deltaNeutronObjectUpdate();
+        deltaNeutronFloatingIP.setPortUUID(null);
+        when(mockedApiConnector.findById(FloatingIp.class, neutronFloatingIP.getFloatingIPUUID())).thenReturn(mockedFloatingIp);
+        when(mockedApiConnector.update(mockedFloatingIp)).thenReturn(false);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, floatingIphandler.canUpdateFloatingIP(deltaNeutronFloatingIP, neutronFloatingIP));
+    }
+
+    /* Test method to check if can update FloatingIP updated */
+    @Test
+    public void testcanUpdateFloatingIPTrue() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        NeutronFloatingIP deltaNeutronFloatingIP = deltaNeutronObjectUpdate();
+        deltaNeutronFloatingIP.setPortUUID(null);
+        when(mockedApiConnector.findById(FloatingIp.class, neutronFloatingIP.getFloatingIPUUID())).thenReturn(mockedFloatingIp);
+        when(mockedApiConnector.update(mockedFloatingIp)).thenReturn(true);
+        assertEquals(HttpURLConnection.HTTP_OK, floatingIphandler.canUpdateFloatingIP(deltaNeutronFloatingIP, neutronFloatingIP));
+    }
+
+    /* Test method to check if can delete FloatingIP Null object */
+    @Test
+    public void testcanDeleteFloatingIPObjNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, floatingIphandler.canDeleteFloatingIP(null));
+    }
+
+    /* Test method to check if can delete FloatingIP not found */
+    @Test
+    public void testcanDeleteFloatingIPNotFound() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronFloatingIP neutronFloatingIP = defaultNeutronObject();
+        when(mockedApiConnector.findById(FloatingIp.class, neutronFloatingIP.getFloatingIPUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, floatingIphandler.canDeleteFloatingIP(neutronFloatingIP));
+    }
+}
index 2c239b46cf8d0196c83e8484ccdfeee064db490c..40c17ab5c56e26d5b5c12088639f65f194cbfb82 100755 (executable)
@@ -18,10 +18,12 @@ import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.UUID;
 
 import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.ApiPropertyBase;
 import net.juniper.contrail.api.ObjectReference;
+import net.juniper.contrail.api.types.FloatingIpPool;
 import net.juniper.contrail.api.types.Project;
 import net.juniper.contrail.api.types.VirtualNetwork;
 
@@ -42,11 +44,13 @@ import org.powermock.modules.junit4.PowerMockRunner;
 @RunWith(PowerMockRunner.class)
 public class NetworkHandlerTest {
     NetworkHandler networkHandler;
+    NetworkHandler mockednetworkHandler = mock(NetworkHandler.class);
     NeutronNetwork mockedNeutronNetwork = mock(NeutronNetwork.class);
     ApiConnector mockedApiConnector = mock(ApiConnector.class);
     ApiConnector mockedApiConnector1 = Mockito.mock(ApiConnector.class);
     VirtualNetwork mockedVirtualNetwork = mock(VirtualNetwork.class);
-    Project mockProject = mock(Project.class);
+    Project mockedProject = mock(Project.class);
+    FloatingIpPool mockedFloatingIpPool = mock(FloatingIpPool.class);
 
     @Before
     public void beforeTest() {
@@ -54,7 +58,8 @@ public class NetworkHandlerTest {
         assertNotNull(mockedApiConnector);
         assertNotNull(mockedNeutronNetwork);
         assertNotNull(mockedVirtualNetwork);
-        assertNotNull(mockProject);
+        assertNotNull(mockedProject);
+        assertNotNull(mockedFloatingIpPool);
     }
 
     @After
@@ -69,28 +74,40 @@ public class NetworkHandlerTest {
         neutron.setNetworkName("Virtual-Network");
         neutron.setNetworkUUID("6b9570f2-17b1-4fc3-99ec-1b7f7778a29a");
         neutron.setProviderNetworkType("gre");
-        neutron.setTenantID("019570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setTenantID("123570f2-17b1-4fc3-99ec-1b7f7778a29a");
         neutron.setProviderSegmentationID("2");
         neutron.setAdminStateUp(true);
         neutron.setProviderNetworkType("gre");
         neutron.setProviderSegmentationID("2");
         neutron.setShared(false);
         neutron.setRouterExternal(false);
+        neutron.setRouterExternal(true);
         return neutron;
     }
 
     /* dummy params for Neutron Network for update */
     public NeutronNetwork defaultNeutronObjectUpdate() {
-        NeutronNetwork delta_neutron = new NeutronNetwork();
-        delta_neutron.setNetworkName("Virtual-Network-2");
-        delta_neutron.setTenantID("cfedfe89b66e406aad56052873c683e7");
-        delta_neutron.setProviderSegmentationID("3");
-        delta_neutron.setAdminStateUp(true);
-        delta_neutron.setProviderNetworkType("gre");
-        delta_neutron.setProviderSegmentationID("4");
-        delta_neutron.setShared(false);
-        delta_neutron.setRouterExternal(false);
-        return delta_neutron;
+        NeutronNetwork deltaNetwork = new NeutronNetwork();
+        deltaNetwork.setNetworkName("Virtual-Network-2");
+        deltaNetwork.setTenantID("123570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        deltaNetwork.setProviderSegmentationID("3");
+        deltaNetwork.setAdminStateUp(true);
+        deltaNetwork.setProviderNetworkType("gre");
+        deltaNetwork.setProviderSegmentationID("4");
+        deltaNetwork.setShared(true);
+        deltaNetwork.setRouterExternal(false);
+        deltaNetwork.setRouterExternal(true);
+        return deltaNetwork;
+    }
+
+    /* dummy params for Nfloating IP */
+    public FloatingIpPool defaultFloatingIpPoolObject() {
+        FloatingIpPool floatingIpPoolObj = new FloatingIpPool();
+        String fipId = UUID.randomUUID().toString();
+        floatingIpPoolObj.setName(fipId);
+        floatingIpPoolObj.setDisplayName(fipId);
+        floatingIpPoolObj.setUuid(fipId);
+        return floatingIpPoolObj;
     }
 
     /* Test method to check if neutron network is null */
@@ -110,23 +127,38 @@ public class NetworkHandlerTest {
         assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canCreateNetwork(neutron));
     }
 
-    /* Test method to check if neutron network uuid is empty or name is null */
+    /*
+     * Test method to check if neutron network uuid is empty or name is null
+     */
     @Test
     public void testCanCreateNetworkUuidEmpty() {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutron = new NeutronNetwork();
         neutron.setNetworkUUID("");
-        neutron.setNetworkName(null);
+        neutron.setNetworkName("");
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canCreateNetwork(neutron));
+    }
+
+    /* Test method to check if neutron network TenantID is null */
+    @Test
+    public void testCanCreateNetworkTenantIDNull() {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronNetwork neutron = new NeutronNetwork();
+        neutron.setNetworkName("net-1");
+        neutron.setNetworkUUID("6b9570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setTenantID(null);
         assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canCreateNetwork(neutron));
     }
 
-    /* Test method to check if neutron network tenant id is null */
+    /*
+     * Test method to check neutron network with virtual project UUID Existence
+     */
     @Test
-    public void testCanCreateNetworkTenantIdNull() {
+    public void testcanCreateNetworkProjectUUIDNull() throws IOException {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        neutronNetwork.setTenantID(null);
-        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canCreateNetwork(neutronNetwork));
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, networkHandler.canCreateNetwork(neutronNetwork));
     }
 
     /* Test method to check neutron network with virtual network Existence */
@@ -135,121 +167,224 @@ public class NetworkHandlerTest {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
         when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
-        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockProject);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
         assertEquals(HttpURLConnection.HTTP_FORBIDDEN, networkHandler.canCreateNetwork(neutronNetwork));
     }
 
-    /*
-     * Test method to check neutron network creation fails with Internal Server
-     * Error
-     */
+    /* Test method to check neutron network create Failed */
     @Test
-    public void testCanCreateNetworkInternalError() throws Exception {
-        VirtualNetwork mockInstance = PowerMock.createNiceMock(VirtualNetwork.class);
+    public void testCanCreateNetworkFailed() throws Exception {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        expectNew(VirtualNetwork.class).andReturn(mockInstance);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
         when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(null);
-        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockProject);
-        when(mockedApiConnector.create(mockInstance)).thenReturn(false);
-        PowerMock.replay(mockInstance, VirtualNetwork.class);
+        VirtualNetwork mockedVirtualNet = PowerMock.createNiceMock(VirtualNetwork.class);
+        expectNew(VirtualNetwork.class).andReturn(mockedVirtualNet);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
+        when(mockedApiConnector.create(mockedVirtualNet)).thenReturn(false);
+        PowerMock.replay(mockedVirtualNet, VirtualNetwork.class);
         assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, networkHandler.canCreateNetwork(neutronNetwork));
     }
 
-    /* Test method to check network is created */
+    /* Test method to check neutron network create with HTTP OK */
     @Test
-    public void testCanCreateNetworkHttpOk() throws Exception {
-        VirtualNetwork mockInstance = PowerMock.createNiceMock(VirtualNetwork.class);
+    public void testCanCreateNetworkOK() throws Exception {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        expectNew(VirtualNetwork.class).andReturn(mockInstance);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
         when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(null);
-        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockProject);
-        when(mockedApiConnector.create(mockInstance)).thenReturn(true);
-        PowerMock.replay(mockInstance, VirtualNetwork.class);
+        VirtualNetwork mockedVirtualNet = PowerMock.createNiceMock(VirtualNetwork.class);
+        expectNew(VirtualNetwork.class).andReturn(mockedVirtualNet);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
+        when(mockedApiConnector.create(mockedVirtualNet)).thenReturn(true);
+        PowerMock.replay(mockedVirtualNet, VirtualNetwork.class);
         assertEquals(HttpURLConnection.HTTP_OK, networkHandler.canCreateNetwork(neutronNetwork));
     }
 
-    /* Test method to check neutron network with virtual network Existence */
+    /* Test method to check if neutron network is null */
     @Test
-    public void testcanCreateNetworkProjectNull() throws IOException {
+    public void testCanUpdateNetworkNull() {
         Activator.apiConnector = mockedApiConnector;
-        NeutronNetwork neutronNetwork = defaultNeutronObject();
-        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(null);
-        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(null);
-        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, networkHandler.canCreateNetwork(neutronNetwork));
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canUpdateNetwork(null, null));
     }
 
-    /* Test method to check neutron network with virtual network Existence */
+    /*
+     * Test method to check if neutron network update with null virtual network
+     */
     @Test
-    public void testcanDeleteNetwork() throws IOException {
+    public void testCanUpdateNetworkVirtualNetworkNull() throws IOException {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
+        NeutronNetwork deltaNeutronNetwork = defaultNeutronObjectUpdate();
         when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(null);
-        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canDeleteNetwork(neutronNetwork));
+        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, networkHandler.canUpdateNetwork(deltaNeutronNetwork, neutronNetwork));
     }
 
-    /* Test method to check delete network with when Port exist */
+    /* Test method to check if neutron network update OK */
     @Test
-    public void testcanDeleteNetworkPortExists() throws IOException {
+    public void testCanUpdateNetworkFailed() throws Exception {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
+        NeutronNetwork deltaNeutronNetwork = defaultNeutronObjectUpdate();
         when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
-        List<ObjectReference<ApiPropertyBase>> test = new ArrayList<ObjectReference<ApiPropertyBase>>();
-        when(mockedVirtualNetwork.getVirtualMachineInterfaceBackRefs()).thenReturn(test);
-        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, networkHandler.canDeleteNetwork(neutronNetwork));
+        when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(false);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, networkHandler.canUpdateNetwork(deltaNeutronNetwork, neutronNetwork));
     }
 
-    /* Test method to check if neutron network is null */
+    /* Test method to check if neutron network update create Foating IP failed */
     @Test
-    public void testCanUpdateNetworkNull() {
+    public void testCanUpdateNetworkCreateFloatingIpFailed() throws Exception {
         Activator.apiConnector = mockedApiConnector;
-        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canUpdateNetwork(null, null));
+        NeutronNetwork neutronNetwork = defaultNeutronObject();
+        NeutronNetwork deltaNeutronNetwork = defaultNeutronObjectUpdate();
+        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
+        when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(true);
+        neutronNetwork.setRouterExternal(false);
+        deltaNeutronNetwork.setRouterExternal(true);
+        when(mockedApiConnector.findById(VirtualNetwork.class, mockedVirtualNetwork.getUuid())).thenReturn(mockedVirtualNetwork);
+        FloatingIpPool floatingIpPool = PowerMock.createNiceMock(FloatingIpPool.class);
+        expectNew(FloatingIpPool.class).andReturn(floatingIpPool);
+        floatingIpPool.setParent(mockedVirtualNetwork);
+        when(mockedApiConnector.create(floatingIpPool)).thenReturn(false);
+        PowerMock.replay(floatingIpPool, FloatingIpPool.class);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, networkHandler.canUpdateNetwork(deltaNeutronNetwork, neutronNetwork));
+
     }
 
-    /* Test method to check if neutron network is null */
+    /*
+     * Test method to check neutron network updated successfully after
+     * floatingIP created
+     */
     @Test
-    public void testCanUpdateNetworkEmptyName() {
+    public void testCanUpdateNetworkOKif() throws Exception {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        NeutronNetwork delta_neutronNetwork = defaultNeutronObjectUpdate();
-        delta_neutronNetwork.setNetworkName("");
-        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canUpdateNetwork(delta_neutronNetwork, neutronNetwork));
+        NeutronNetwork deltaNetwork = defaultNeutronObjectUpdate();
+        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
+        mockedVirtualNetwork.setName(deltaNetwork.getNetworkName());
+        mockedVirtualNetwork.setDisplayName(deltaNetwork.getNetworkName());
+        when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(true);
+        neutronNetwork.setRouterExternal(false);
+        deltaNetwork.setRouterExternal(true);
+        when(mockedApiConnector.findById(VirtualNetwork.class, mockedVirtualNetwork.getUuid())).thenReturn(mockedVirtualNetwork);
+        FloatingIpPool floatingIpPool = PowerMock.createNiceMock(FloatingIpPool.class);
+        expectNew(FloatingIpPool.class).andReturn(floatingIpPool);
+        String fipId = UUID.randomUUID().toString();
+        floatingIpPool.setName(fipId);
+        floatingIpPool.setDisplayName(fipId);
+        floatingIpPool.setUuid(fipId);
+        floatingIpPool.setParent(mockedVirtualNetwork);
+        when(mockedApiConnector.create(floatingIpPool)).thenReturn(true);
+        PowerMock.replay(floatingIpPool, FloatingIpPool.class);
+        assertEquals(HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(deltaNetwork, neutronNetwork));
     }
 
-    /* Test method to check neutron network with virtual network Existence */
+    // /* Test method to check neutron network updated failed due to Floating Ip
+    // pool is failed to removed after update network..*/
+    // @Test
+    // public void testupdateNetworkFloatingIPremoveFailed() throws Exception {
+    // Activator.apiConnector = mockedApiConnector;
+    // NeutronNetwork neutronNetwork = defaultNeutronObject();
+    // NeutronNetwork deltaNetwork =defaultNeutronObjectUpdate();
+    // when(mockedApiConnector.findById(VirtualNetwork.class,neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
+    // mockedVirtualNetwork.setName(deltaNetwork.getNetworkName());
+    // mockedVirtualNetwork.setDisplayName(deltaNetwork.getNetworkName());
+    // when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(true);
+    // neutronNetwork.setRouterExternal(true);
+    // deltaNetwork.setRouterExternal(false);
+    // ObjectReference<ApiPropertyBase> ref = new ObjectReference<>();
+    // List<ObjectReference<ApiPropertyBase>> pool = new
+    // ArrayList<ObjectReference<ApiPropertyBase>>();
+    // FloatingIpPool fp = new FloatingIpPool();
+    // List<String> temp = new ArrayList<String>();
+    // for (int i = 0; i < 1; i++) {
+    // String fipId = UUID.randomUUID().toString();
+    // fp.setDisplayName(fipId);
+    // fp.setName(fipId);
+    // fp.setUuid(fipId);
+    // ref.setReference(temp,"", "",""); //To do do not have api property base
+    // reference
+    // pool.add(i, ref);
+    // }
+    // when(mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid()).thenReturn("000570f2-17b1-4fc3-99ec-1b7f7778a29a");
+    // when(mockedApiConnector.findById(FloatingIpPool.class,mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid())).thenReturn(mockedFloatingIpPool);
+    // when(mockedApiConnector.findById(FloatingIpPool.class,mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid())).thenReturn(mockedFloatingIpPool);
+    // PowerMock.replay(floatingIpPool, FloatingIpPool.class);
+    // assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR,networkHandler.canUpdateNetwork(deltaNetwork,
+    // neutronNetwork));
+    // }
+
+    // /* Test method to check neutron network updated successfully after
+    // floatingIP removal..*/
+    // @Test
+    // public void testupdateNetworkOKelse() throws Exception {
+    // Activator.apiConnector = mockedApiConnector;
+    // NeutronNetwork neutronNetwork = defaultNeutronObject();
+    // NeutronNetwork deltaNetwork =defaultNeutronObjectUpdate();
+    // when(mockedApiConnector.findById(VirtualNetwork.class,neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
+    // mockedVirtualNetwork.setName(deltaNetwork.getNetworkName());
+    // mockedVirtualNetwork.setDisplayName(deltaNetwork.getNetworkName());
+    // when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(true);
+    // neutronNetwork.setRouterExternal(true);
+    // deltaNetwork.setRouterExternal(false);
+    // ObjectReference<ApiPropertyBase> ref = new ObjectReference<>();
+    // List<ObjectReference<ApiPropertyBase>> pool = new
+    // ArrayList<ObjectReference<ApiPropertyBase>>();
+    // FloatingIpPool fp = new FloatingIpPool();
+    // List<String> temp = new ArrayList<String>();
+    // for (int i = 0; i < 1; i++) {
+    // String fipId = UUID.randomUUID().toString();
+    // fp.setDisplayName(fipId);
+    // fp.setName(fipId);
+    // fp.setUuid(fipId);
+    // ref.setReference(temp,"", "","");//To do do not have api property base
+    // reference
+    // pool.add(i, ref);
+    // }
+    // when(mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid()).thenReturn("000570f2-17b1-4fc3-99ec-1b7f7778a29a");
+    // when(mockedApiConnector.findById(FloatingIpPool.class,mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid())).thenReturn(mockedFloatingIpPool);
+    // when(mockedApiConnector.findById(FloatingIpPool.class,mockedVirtualNetwork.getFloatingIpPools().get(0).getUuid())).thenReturn(null);
+    //
+    // assertEquals(HttpURLConnection.HTTP_OK,
+    // networkHandler.canUpdateNetwork(deltaNetwork, neutronNetwork));
+    // }
+
+    /* Test method to check delete network with when Port exist */
     @Test
-    public void testCanUpdateNetworkVirtualNetworkNotExists() throws IOException {
+    public void testcanDeleteNetworkPortExists() throws IOException {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        NeutronNetwork delta_neutronNetwork = defaultNeutronObjectUpdate();
-        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(null);
-        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, networkHandler.canUpdateNetwork(delta_neutronNetwork, neutronNetwork));
+        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
+        List<ObjectReference<ApiPropertyBase>> test = new ArrayList<ObjectReference<ApiPropertyBase>>();
+        when(mockedVirtualNetwork.getVirtualMachineInterfaceBackRefs()).thenReturn(test);
+        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, networkHandler.canDeleteNetwork(neutronNetwork));
     }
 
     /*
-     * Test method to check neutron network update fails with Internal Server
-     * Error
+     * Test method to check neutron network deletion with virtual network
+     * Existence
      */
     @Test
-    public void testUpdateNetworkInternalError() throws IOException {
+    public void testcanDeleteNetwork() throws IOException {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        NeutronNetwork delta_neutronNetwork = defaultNeutronObjectUpdate();
-        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
-        when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(false);
-        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, networkHandler.canUpdateNetwork(delta_neutronNetwork, neutronNetwork));
+        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, networkHandler.canDeleteNetwork(neutronNetwork));
     }
 
-    /* Test method to check neutron network update with HTTP OK */
+    /*
+     * Test method to check neutron network creation of virtual network failed
+     */
     @Test
-    public void testUpdateNetwork() throws IOException {
+    public void testcreateNetworkVirtualNetworkFalse() throws Exception {
         Activator.apiConnector = mockedApiConnector;
         NeutronNetwork neutronNetwork = defaultNeutronObject();
-        NeutronNetwork delta_neutronNetwork = defaultNeutronObjectUpdate();
-        mockedVirtualNetwork.setName(delta_neutronNetwork.getNetworkName());
-        when(mockedApiConnector.findById(VirtualNetwork.class, neutronNetwork.getNetworkUUID())).thenReturn(mockedVirtualNetwork);
-        when(mockedApiConnector.update(mockedVirtualNetwork)).thenReturn(true);
-        assertEquals(HttpURLConnection.HTTP_OK, networkHandler.canUpdateNetwork(delta_neutronNetwork, neutronNetwork));
+        VirtualNetwork mockedVirtualNet = PowerMock.createNiceMock(VirtualNetwork.class);
+        expectNew(VirtualNetwork.class).andReturn(mockedVirtualNet);
+        when(mockedApiConnector.findById(Project.class, neutronNetwork.getTenantID())).thenReturn(mockedProject);
+        when(mockedApiConnector.create(mockedVirtualNet)).thenReturn(false);
+        PowerMock.replay(mockedVirtualNet, VirtualNetwork.class);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, networkHandler.canCreateNetwork(neutronNetwork));
     }
-}
\ No newline at end of file
+
+}
diff --git a/neutron/src/test/java/org/opendaylight/plugin2oc/neutron/RouterHandlerTest.java b/neutron/src/test/java/org/opendaylight/plugin2oc/neutron/RouterHandlerTest.java
new file mode 100755 (executable)
index 0000000..edad738
--- /dev/null
@@ -0,0 +1,315 @@
+package org.opendaylight.plugin2oc.neutron;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.powermock.api.easymock.PowerMock.expectNew;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.types.LogicalRouter;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.types.VirtualMachine;
+import net.juniper.contrail.api.types.VirtualMachineInterface;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opendaylight.controller.networkconfig.neutron.NeutronRouter;
+import org.opendaylight.controller.networkconfig.neutron.NeutronRouter_Interface;
+import org.opendaylight.controller.networkconfig.neutron.NeutronRouter_NetworkReference;
+import org.powermock.api.easymock.PowerMock;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ RouterHandler.class, LogicalRouter.class })
+public class RouterHandlerTest {
+
+    RouterHandler routerHandler;
+    RouterHandler mockedRouterHandler = mock(RouterHandler.class);
+    NeutronRouter mockedNeutronRouter = mock(NeutronRouter.class);
+    LogicalRouter mockedLogicalRouter = mock(LogicalRouter.class);
+    ApiConnector mockedApiConnector = mock(ApiConnector.class);
+    Project mockedProject = mock(Project.class);
+    NeutronRouter_Interface mockNeutronRouter_Interface = mock(NeutronRouter_Interface.class);
+    VirtualMachineInterface mockVirtualMachineInterface = mock(VirtualMachineInterface.class);
+
+    @Before
+    public void beforeTest() {
+        routerHandler = new RouterHandler();
+        assertNotNull(mockedRouterHandler);
+        assertNotNull(mockedApiConnector);
+        assertNotNull(mockedNeutronRouter);
+        assertNotNull(mockedLogicalRouter);
+        assertNotNull(mockedProject);
+        assertNotNull(mockNeutronRouter_Interface);
+        assertNotNull(mockVirtualMachineInterface);
+    }
+
+    @After
+    public void AfterTest() {
+        routerHandler = null;
+        Activator.apiConnector = null;
+    }
+
+    /* dummy params for Neutron Router */
+
+    public NeutronRouter defaultNeutronObject() {
+        NeutronRouter neutron = new NeutronRouter();
+        NeutronRouter_NetworkReference neuRouter_NetworkReference = new NeutronRouter_NetworkReference();
+        neuRouter_NetworkReference.setNetworkID("009570f2-17b1-4fc3-99ec-1b7f7778a29b");
+        neutron.setAdminStateUp(true);
+        neutron.setName("Router-01");
+        neutron.setRouterUUID("009570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setTenantID("119570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setStatus("ACTIVE");
+        neutron.setExternalGatewayInfo(neuRouter_NetworkReference);
+        return neutron;
+    }
+
+    /* dummy params for Neutron Router update */
+
+    public NeutronRouter deltaNeutronObject() {
+        NeutronRouter neutron = new NeutronRouter();
+        neutron.setAdminStateUp(true);
+        neutron.setName("Router-02");
+        neutron.setRouterUUID("009570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setTenantID("119570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutron.setStatus("ACTIVE");
+        neutron.setExternalGatewayInfo(null);
+        return neutron;
+    }
+
+    /* dummy params for NeutronRouter_Interface */
+
+    public NeutronRouter_Interface deltaNeutronRouter_Interface() {
+        NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface();
+        neutronRouterInterface.setID("009570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutronRouterInterface.setPortUUID("119570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutronRouterInterface.setSubnetUUID("229570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        neutronRouterInterface.setTenantID("339570f2-17b1-4fc3-99ec-1b7f7778a29a");
+        return neutronRouterInterface;
+    }
+
+    /* Test method to check if neutron router object is null */
+    @Test
+    public void testCanCreateRouterNull() {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canCreateRouter(null));
+    }
+
+    /* Test method to check if neutron router UUID is null */
+    @Test
+    public void testCanCreateRouterNullUUID() {
+        Activator.apiConnector = mockedApiConnector;
+        when(mockedNeutronRouter.getRouterUUID()).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canCreateRouter(mockedNeutronRouter));
+    }
+
+    /* Test method to check if neutron router name is null */
+    @Test
+    public void testCanCreateRouterNullName() {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        neutronRouter.setName(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canCreateRouter(neutronRouter));
+    }
+
+    /* Test method to check if tenant ID is null */
+    @Test
+    public void testCanCreateRouterNullTenantID() {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        neutronRouter.setTenantID(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canCreateRouter(neutronRouter));
+    }
+
+    /* Test method to check if router Project UUID not found */
+    @Test
+    public void testCanCreateRouterProjectUUIDnull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        when(mockedApiConnector.findById(Project.class, neutronRouter.getTenantID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, routerHandler.canCreateRouter(neutronRouter));
+    }
+
+    /* Test method to check if router creation fails */
+    @Test
+    public void testCanCreateRouterFails() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        LogicalRouter lr = PowerMock.createNiceMock(LogicalRouter.class);
+        expectNew(LogicalRouter.class).andReturn(lr);
+        when(mockedApiConnector.findById(Project.class, neutronRouter.getTenantID())).thenReturn(mockedProject);
+        lr.setParent(mockedProject);
+        when(mockedApiConnector.create(lr)).thenReturn(false);
+        PowerMock.replay(lr, LogicalRouter.class);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, routerHandler.canCreateRouter(neutronRouter));
+    }
+
+    /* Test method to check if router created */
+    @Test
+    public void testCanCreateRouterOK() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        LogicalRouter lr = PowerMock.createNiceMock(LogicalRouter.class);
+        expectNew(LogicalRouter.class).andReturn(lr);
+        when(mockedApiConnector.findById(Project.class, neutronRouter.getTenantID())).thenReturn(mockedProject);
+        lr.setParent(mockedProject);
+        when(mockedApiConnector.create(lr)).thenReturn(true);
+        PowerMock.replay(lr, LogicalRouter.class);
+        assertEquals(HttpURLConnection.HTTP_OK, routerHandler.canCreateRouter(neutronRouter));
+    }
+
+    /* Test method to check if neutron router is null for delete */
+    @Test
+    public void testcanDeleteRouterNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canDeleteRouter(null));
+    }
+
+    /* Test method to check if delete router that does not exist */
+    @Test
+    public void testcanDeleteRouterBadRequest() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canDeleteRouter(neutronRouter));
+    }
+
+    /* Test method to check if can update router Null object */
+    @Test
+    public void testcanUpdateRouterObjNull() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, routerHandler.canUpdateRouter(null, null));
+    }
+
+    /* Test method to check if can update router object not found */
+    @Test
+    public void testcanUpdateRouterObjNotFound() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter deltaRouter = deltaNeutronObject();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(null);
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, routerHandler.canUpdateRouter(neutronRouter, deltaRouter));
+    }
+
+    /* Test method to check if can update router object not found */
+    @Test
+    public void testcanUpdateRouterFailed() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter deltaRouter = deltaNeutronObject();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.update(mockedLogicalRouter)).thenReturn(false);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, routerHandler.canUpdateRouter(neutronRouter, deltaRouter));
+    }
+
+    /* Test method to check if can update router object not founf=d */
+    @Test
+    public void testcanUpdateRouterOK() throws IOException {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter deltaRouter = deltaNeutronObject();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.update(mockedLogicalRouter)).thenReturn(true);
+        assertEquals(HttpURLConnection.HTTP_OK, routerHandler.canUpdateRouter(neutronRouter, deltaRouter));
+    }
+
+    /* Test method to check if canAttachInterface update vmi failed */
+    @Test
+    public void testcanAttachInterfaceVMIfailed() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter_Interface neutronRouterInterface = deltaNeutronRouter_Interface();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.findById(VirtualMachineInterface.class, neutronRouterInterface.getPortUUID()))
+                .thenReturn(mockVirtualMachineInterface);
+        mockedLogicalRouter.setVirtualMachineInterface(mockVirtualMachineInterface);
+        VirtualMachine vm = PowerMock.createNiceMock(VirtualMachine.class);
+        expectNew(VirtualMachine.class).andReturn(vm);
+        vm.setName(neutronRouter.getRouterUUID());
+        vm.setUuid(neutronRouter.getRouterUUID());
+        mockVirtualMachineInterface.setVirtualMachine(vm);
+        when(mockedApiConnector.update(mockVirtualMachineInterface)).thenReturn(false);
+        PowerMock.replay(vm, VirtualMachine.class);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, routerHandler.canAttachInterface(neutronRouter, neutronRouterInterface));
+    }
+
+    /*
+     * Test method to check if canAttachInterface update vmi successfully but
+     * attach interface failed
+     */
+    @Test
+    public void testcanAttachInterfaceVMIOk() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter_Interface neutronRouterInterface = deltaNeutronRouter_Interface();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.findById(VirtualMachineInterface.class, neutronRouterInterface.getPortUUID()))
+                .thenReturn(mockVirtualMachineInterface);
+        mockedLogicalRouter.setVirtualMachineInterface(mockVirtualMachineInterface);
+        VirtualMachine vm = PowerMock.createNiceMock(VirtualMachine.class);
+        expectNew(VirtualMachine.class).andReturn(vm);
+        vm.setName(neutronRouter.getRouterUUID());
+        vm.setUuid(neutronRouter.getRouterUUID());
+        mockVirtualMachineInterface.setVirtualMachine(vm);
+        when(mockedApiConnector.update(mockVirtualMachineInterface)).thenReturn(true);
+        PowerMock.replay(vm, VirtualMachine.class);
+        when(mockedApiConnector.update(mockedLogicalRouter)).thenReturn(false);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, routerHandler.canAttachInterface(neutronRouter, neutronRouterInterface));
+    }
+
+    /* Test method to check if interface is attached successfully */
+    @Test
+    public void testcanAttachInterfaceOK() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter_Interface neutronRouterInterface = deltaNeutronRouter_Interface();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.findById(VirtualMachineInterface.class, neutronRouterInterface.getPortUUID()))
+                .thenReturn(mockVirtualMachineInterface);
+        mockedLogicalRouter.setVirtualMachineInterface(mockVirtualMachineInterface);
+        VirtualMachine vm = PowerMock.createNiceMock(VirtualMachine.class);
+        expectNew(VirtualMachine.class).andReturn(vm);
+        vm.setName(neutronRouter.getRouterUUID());
+        vm.setUuid(neutronRouter.getRouterUUID());
+        mockVirtualMachineInterface.setVirtualMachine(vm);
+        when(mockedApiConnector.update(mockVirtualMachineInterface)).thenReturn(true);
+        PowerMock.replay(vm, VirtualMachine.class);
+        when(mockedApiConnector.update(mockedLogicalRouter)).thenReturn(true);
+        assertEquals(HttpURLConnection.HTTP_OK, routerHandler.canAttachInterface(neutronRouter, neutronRouterInterface));
+    }
+
+    /* Test method to check if canDetachInterface update vmi failed */
+    @Test
+    public void testcanDetachInterfaceVMIfailed() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter_Interface neutronRouterInterface = deltaNeutronRouter_Interface();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.findById(VirtualMachineInterface.class, neutronRouterInterface.getPortUUID()))
+                .thenReturn(mockVirtualMachineInterface);
+        when(mockedApiConnector.update(mockVirtualMachineInterface)).thenReturn(false);
+        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, routerHandler.canDetachInterface(neutronRouter, neutronRouterInterface));
+    }
+
+    /* Test method to check if interface is detached succesfully */
+    @Test
+    public void testcanDetachInterfaceOK() throws Exception {
+        Activator.apiConnector = mockedApiConnector;
+        NeutronRouter neutronRouter = defaultNeutronObject();
+        NeutronRouter_Interface neutronRouterInterface = deltaNeutronRouter_Interface();
+        when(mockedApiConnector.findById(LogicalRouter.class, neutronRouter.getRouterUUID())).thenReturn(mockedLogicalRouter);
+        when(mockedApiConnector.findById(VirtualMachineInterface.class, neutronRouterInterface.getPortUUID()))
+                .thenReturn(mockVirtualMachineInterface);
+        when(mockedApiConnector.update(mockVirtualMachineInterface)).thenReturn(true);
+        when(mockedApiConnector.update(mockedLogicalRouter)).thenReturn(true);
+        assertEquals(HttpURLConnection.HTTP_OK, routerHandler.canDetachInterface(neutronRouter, neutronRouterInterface));
+    }
+}
\ No newline at end of file
index 5927156d635059d3602819baaf6cabcdac097e0b..f5964b7d5896ea2158dfab501d33125b21cde5f7 100755 (executable)
@@ -59,6 +59,7 @@ public class SubnetHandlerTest {
         neutronSubnet_IPAllocationPool.setPoolEnd("10.0.0.254");
         allocationPools.add(neutronSubnet_IPAllocationPool);
         subnet.setAllocationPools(allocationPools);
+        subnet.setEnableDHCP(true);
         return subnet;
     }