Fix for bugs 446 and 456
[controller.git] / opendaylight / northbound / networkconfiguration / neutron / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / NeutronPortsNorthbound.java
index 78646a6383e38131c4e7df4100c318fe6ab5a2cb..9f24e79ea02ab3fd6fbbd722fe8c86054a3b4470 100644 (file)
-/*\r
- * Copyright IBM Corporation, 2013.  All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.controller.networkconfig.neutron.northbound;\r
-\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import javax.ws.rs.Consumes;\r
-import javax.ws.rs.DELETE;\r
-import javax.ws.rs.GET;\r
-import javax.ws.rs.POST;\r
-import javax.ws.rs.PUT;\r
-import javax.ws.rs.Path;\r
-import javax.ws.rs.PathParam;\r
-import javax.ws.rs.Produces;\r
-import javax.ws.rs.QueryParam;\r
-import javax.ws.rs.core.MediaType;\r
-import javax.ws.rs.core.Response;\r
-\r
-import org.codehaus.enunciate.jaxrs.ResponseCode;\r
-import org.codehaus.enunciate.jaxrs.StatusCodes;\r
-import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;\r
-import org.opendaylight.controller.networkconfig.neutron.INeutronPortAware;\r
-import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;\r
-import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetAware;\r
-import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;\r
-import org.opendaylight.controller.networkconfig.neutron.NeutronPort;\r
-import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;\r
-import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;\r
-import org.opendaylight.controller.northbound.commons.RestMessages;\r
-import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;\r
-import org.opendaylight.controller.sal.utils.ServiceHelper;\r
-\r
-/**\r
- * Open DOVE Northbound REST APIs.<br>\r
- * This class provides REST APIs for managing the open DOVE\r
- *\r
- * <br>\r
- * <br>\r
- * Authentication scheme : <b>HTTP Basic</b><br>\r
- * Authentication realm : <b>opendaylight</b><br>\r
- * Transport : <b>HTTP and HTTPS</b><br>\r
- * <br>\r
- * HTTPS Authentication is disabled by default. Administrator can enable it in\r
- * tomcat-server.xml after adding a proper keystore / SSL certificate from a\r
- * trusted authority.<br>\r
- * More info :\r
- * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration\r
- *\r
- */\r
-\r
-@Path("/ports")\r
-public class NeutronPortsNorthbound {\r
-\r
-    private NeutronPort extractFields(NeutronPort o, List<String> fields) {\r
-        return o.extractFields(fields);\r
-    }\r
-\r
-    /**\r
-     * Returns a list of all Ports */\r
-\r
-    @GET\r
-    @Produces({ MediaType.APPLICATION_JSON })\r
-    //@TypeHint(OpenStackPorts.class)\r
-    @StatusCodes({\r
-            @ResponseCode(code = 200, condition = "Operation successful"),\r
-            @ResponseCode(code = 401, condition = "Unauthorized"),\r
-            @ResponseCode(code = 501, condition = "Not Implemented") })\r
-    public Response listPorts(\r
-            // return fields\r
-            @QueryParam("fields") List<String> fields,\r
-            // note: openstack isn't clear about filtering on lists, so we aren't handling them\r
-            @QueryParam("id") String queryID,\r
-            @QueryParam("network_id") String queryNetworkID,\r
-            @QueryParam("name") String queryName,\r
-            @QueryParam("admin_state_up") String queryAdminStateUp,\r
-            @QueryParam("status") String queryStatus,\r
-            @QueryParam("mac_address") String queryMACAddress,\r
-            @QueryParam("device_id") String queryDeviceID,\r
-            @QueryParam("device_owner") String queryDeviceOwner,\r
-            @QueryParam("tenant_id") String queryTenantID,\r
-            // pagination\r
-            @QueryParam("limit") String limit,\r
-            @QueryParam("marker") String marker,\r
-            @QueryParam("page_reverse") String pageReverse\r
-            // sorting not supported\r
-            ) {\r
-        INeutronPortCRUD portInterface = NeutronNBInterfaces.getIfNBPortCRUD("default",this);\r
-        if (portInterface == null) {\r
-            throw new ServiceUnavailableException("Port CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        List<NeutronPort> allPorts = portInterface.getAllPorts();\r
-        List<NeutronPort> ans = new ArrayList<NeutronPort>();\r
-        Iterator<NeutronPort> i = allPorts.iterator();\r
-        while (i.hasNext()) {\r
-            NeutronPort oSS = i.next();\r
-            if ((queryID == null || queryID.equals(oSS.getID())) &&\r
-                    (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&\r
-                    (queryName == null || queryName.equals(oSS.getName())) &&\r
-                    (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&\r
-                    (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&\r
-                    (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&\r
-                    (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&\r
-                    (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&\r
-                    (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {\r
-                if (fields.size() > 0)\r
-                    ans.add(extractFields(oSS,fields));\r
-                else\r
-                    ans.add(oSS);\r
-            }\r
-        }\r
-        //TODO: apply pagination to results\r
-        return Response.status(200).entity(\r
-                new NeutronPortRequest(ans)).build();\r
-    }\r
-\r
-    /**\r
-     * Returns a specific Port */\r
-\r
-    @Path("{portUUID}")\r
-    @GET\r
-    @Produces({ MediaType.APPLICATION_JSON })\r
-    //@TypeHint(OpenStackPorts.class)\r
-    @StatusCodes({\r
-            @ResponseCode(code = 200, condition = "Operation successful"),\r
-            @ResponseCode(code = 401, condition = "Unauthorized"),\r
-            @ResponseCode(code = 404, condition = "Not Found"),\r
-            @ResponseCode(code = 501, condition = "Not Implemented") })\r
-    public Response showPort(\r
-            @PathParam("portUUID") String portUUID,\r
-            // return fields\r
-            @QueryParam("fields") List<String> fields ) {\r
-        INeutronPortCRUD portInterface = NeutronNBInterfaces.getIfNBPortCRUD("default",this);\r
-        if (portInterface == null) {\r
-            throw new ServiceUnavailableException("Port CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        if (!portInterface.portExists(portUUID))\r
-            return Response.status(404).build();\r
-        if (fields.size() > 0) {\r
-            NeutronPort ans = portInterface.getPort(portUUID);\r
-            return Response.status(200).entity(\r
-                    new NeutronPortRequest(extractFields(ans, fields))).build();\r
-        } else\r
-            return Response.status(200).entity(\r
-                    new NeutronPortRequest(portInterface.getPort(portUUID))).build();\r
-    }\r
-\r
-    /**\r
-     * Creates new Ports */\r
-\r
-    @POST\r
-    @Produces({ MediaType.APPLICATION_JSON })\r
-    @Consumes({ MediaType.APPLICATION_JSON })\r
-    //@TypeHint(OpenStackPorts.class)\r
-    @StatusCodes({\r
-            @ResponseCode(code = 201, condition = "Created"),\r
-            @ResponseCode(code = 400, condition = "Bad Request"),\r
-            @ResponseCode(code = 401, condition = "Unauthorized"),\r
-            @ResponseCode(code = 403, condition = "Forbidden"),\r
-            @ResponseCode(code = 404, condition = "Not Found"),\r
-            @ResponseCode(code = 409, condition = "Conflict"),\r
-            @ResponseCode(code = 501, condition = "Not Implemented"),\r
-            @ResponseCode(code = 503, condition = "MAC generation failure") })\r
-    public Response createPorts(final NeutronPortRequest input) {\r
-        INeutronPortCRUD portInterface = NeutronNBInterfaces.getIfNBPortCRUD("default",this);\r
-        if (portInterface == null) {\r
-            throw new ServiceUnavailableException("Port CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        INeutronNetworkCRUD networkInterface = NeutronNBInterfaces.getIfNBNetworkCRUD("default", this);\r
-        if (networkInterface == null) {\r
-            throw new ServiceUnavailableException("Network CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        INeutronSubnetCRUD subnetInterface = NeutronNBInterfaces.getIfNBSubnetCRUD("default", this);\r
-        if (subnetInterface == null) {\r
-            throw new ServiceUnavailableException("Subnet CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        if (input.isSingleton()) {\r
-            NeutronPort singleton = input.getSingleton();\r
-\r
-            /*\r
-             * the port must be part of an existing network, must not already exist,\r
-             * have a valid MAC and the MAC not be in use\r
-             */\r
-            if (singleton.getNetworkUUID() == null)\r
-                return Response.status(400).build();\r
-            if (portInterface.portExists(singleton.getID()))\r
-                return Response.status(400).build();\r
-            if (!networkInterface.networkExists(singleton.getNetworkUUID()))\r
-                return Response.status(404).build();\r
-            if (singleton.getMacAddress() == null ||\r
-                    !singleton.getMacAddress().matches("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"))\r
-                return Response.status(400).build();\r
-            if (portInterface.macInUse(singleton.getMacAddress()))\r
-                return Response.status(409).build();\r
-            Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);\r
-            if (instances != null) {\r
-                for (Object instance : instances) {\r
-                    INeutronPortAware service = (INeutronPortAware) instance;\r
-                    int status = service.canCreatePort(singleton);\r
-                    if (status < 200 || status > 299)\r
-                        return Response.status(status).build();\r
-                }\r
-            }\r
-            /*\r
-             * if fixed IPs are specified, each one has to have an existing subnet ID\r
-             * that is in the same scoping network as the port.  In addition, if an IP\r
-             * address is specified it has to be a valid address for the subnet and not\r
-             * already in use\r
-             */\r
-            List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();\r
-            if (fixedIPs != null && fixedIPs.size() > 0) {\r
-                Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();\r
-                while (fixedIPIterator.hasNext()) {\r
-                    Neutron_IPs ip = fixedIPIterator.next();\r
-                    if (ip.getSubnetUUID() == null)\r
-                        return Response.status(400).build();\r
-                    if (!subnetInterface.subnetExists(ip.getSubnetUUID()))\r
-                        return Response.status(400).build();\r
-                    NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());\r
-                    if (!singleton.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))\r
-                        return Response.status(400).build();\r
-                    if (ip.getIpAddress() != null) {\r
-                        if (!subnet.isValidIP(ip.getIpAddress()))\r
-                            return Response.status(400).build();\r
-                        if (subnet.isIPInUse(ip.getIpAddress()))\r
-                            return Response.status(409).build();\r
-                    }\r
-                }\r
-            }\r
-\r
-            // add the port to the cache\r
-            portInterface.addPort(singleton);\r
-            if (instances != null) {\r
-                for (Object instance : instances) {\r
-                    INeutronPortAware service = (INeutronPortAware) instance;\r
-                    service.neutronPortCreated(singleton);\r
-                }\r
-            }\r
-        } else {\r
-            List<NeutronPort> bulk = input.getBulk();\r
-            Iterator<NeutronPort> i = bulk.iterator();\r
-            HashMap<String, NeutronPort> testMap = new HashMap<String, NeutronPort>();\r
-            Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);\r
-            while (i.hasNext()) {\r
-                NeutronPort test = i.next();\r
-\r
-                /*\r
-                 * the port must be part of an existing network, must not already exist,\r
-                 * have a valid MAC and the MAC not be in use.  Further the bulk request\r
-                 * can't already contain a new port with the same UUID\r
-                 */\r
-                if (portInterface.portExists(test.getID()))\r
-                    return Response.status(400).build();\r
-                if (testMap.containsKey(test.getID()))\r
-                    return Response.status(400).build();\r
-                for (NeutronPort check : testMap.values()) {\r
-                    if (test.getMacAddress().equalsIgnoreCase(check.getMacAddress()))\r
-                        return Response.status(409).build();\r
-                    for (Neutron_IPs test_fixedIP : test.getFixedIPs()) {\r
-                        for (Neutron_IPs check_fixedIP : check.getFixedIPs()) {\r
-                            if (test_fixedIP.getIpAddress().equals(check_fixedIP.getIpAddress()))\r
-                                return Response.status(409).build();\r
-                        }\r
-                    }\r
-                }\r
-                testMap.put(test.getID(), test);\r
-                if (!networkInterface.networkExists(test.getNetworkUUID()))\r
-                    return Response.status(404).build();\r
-                if (!test.getMacAddress().matches("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"))\r
-                    return Response.status(400).build();\r
-                if (portInterface.macInUse(test.getMacAddress()))\r
-                    return Response.status(409).build();\r
-                if (instances != null) {\r
-                    for (Object instance : instances) {\r
-                        INeutronPortAware service = (INeutronPortAware) instance;\r
-                        int status = service.canCreatePort(test);\r
-                        if (status < 200 || status > 299)\r
-                            return Response.status(status).build();\r
-                    }\r
-                }\r
-                /*\r
-                 * if fixed IPs are specified, each one has to have an existing subnet ID\r
-                 * that is in the same scoping network as the port.  In addition, if an IP\r
-                 * address is specified it has to be a valid address for the subnet and not\r
-                 * already in use (or be the gateway IP address of the subnet)\r
-                 */\r
-                List<Neutron_IPs> fixedIPs = test.getFixedIPs();\r
-                if (fixedIPs != null && fixedIPs.size() > 0) {\r
-                    Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();\r
-                    while (fixedIPIterator.hasNext()) {\r
-                        Neutron_IPs ip = fixedIPIterator.next();\r
-                        if (ip.getSubnetUUID() == null)\r
-                            return Response.status(400).build();\r
-                        if (!subnetInterface.subnetExists(ip.getSubnetUUID()))\r
-                            return Response.status(400).build();\r
-                        NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());\r
-                        if (!test.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))\r
-                            return Response.status(400).build();\r
-                        if (ip.getIpAddress() != null) {\r
-                            if (!subnet.isValidIP(ip.getIpAddress()))\r
-                                return Response.status(400).build();\r
-                            //TODO: need to add consideration for a fixed IP being assigned the same address as a allocated IP in the\r
-                            //same bulk create\r
-                            if (subnet.isIPInUse(ip.getIpAddress()))\r
-                                return Response.status(409).build();\r
-                        }\r
-                    }\r
-                }\r
-            }\r
-\r
-            //once everything has passed, then we can add to the cache\r
-            i = bulk.iterator();\r
-            while (i.hasNext()) {\r
-                NeutronPort test = i.next();\r
-                portInterface.addPort(test);\r
-                if (instances != null) {\r
-                    for (Object instance : instances) {\r
-                        INeutronPortAware service = (INeutronPortAware) instance;\r
-                        service.neutronPortCreated(test);\r
-                    }\r
-                }\r
-            }\r
-        }\r
-        return Response.status(201).entity(input).build();\r
-    }\r
-\r
-    /**\r
-     * Updates a Port */\r
-\r
-    @Path("{portUUID}")\r
-    @PUT\r
-    @Produces({ MediaType.APPLICATION_JSON })\r
-    @Consumes({ MediaType.APPLICATION_JSON })\r
-    //@TypeHint(OpenStackPorts.class)\r
-    @StatusCodes({\r
-            @ResponseCode(code = 200, condition = "Operation successful"),\r
-            @ResponseCode(code = 400, condition = "Bad Request"),\r
-            @ResponseCode(code = 401, condition = "Unauthorized"),\r
-            @ResponseCode(code = 403, condition = "Forbidden"),\r
-            @ResponseCode(code = 404, condition = "Not Found"),\r
-            @ResponseCode(code = 409, condition = "Conflict"),\r
-            @ResponseCode(code = 501, condition = "Not Implemented") })\r
-    public Response updatePort(\r
-            @PathParam("portUUID") String portUUID,\r
-            NeutronPortRequest input\r
-            ) {\r
-        INeutronPortCRUD portInterface = NeutronNBInterfaces.getIfNBPortCRUD("default",this);\r
-        if (portInterface == null) {\r
-            throw new ServiceUnavailableException("Port CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-        INeutronSubnetCRUD subnetInterface = NeutronNBInterfaces.getIfNBSubnetCRUD("default", this);\r
-        if (subnetInterface == null) {\r
-            throw new ServiceUnavailableException("Subnet CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-\r
-        // port has to exist and only a single delta is supported\r
-        if (!portInterface.portExists(portUUID))\r
-            return Response.status(404).build();\r
-        NeutronPort target = portInterface.getPort(portUUID);\r
-        if (!input.isSingleton())\r
-            return Response.status(400).build();\r
-        NeutronPort singleton = input.getSingleton();\r
-        NeutronPort original = portInterface.getPort(portUUID);\r
-\r
-        // deltas restricted by Neutron\r
-        if (singleton.getID() != null || singleton.getTenantID() != null ||\r
-                singleton.getStatus() != null)\r
-            return Response.status(400).build();\r
-\r
-        Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);\r
-        if (instances != null) {\r
-            for (Object instance : instances) {\r
-                INeutronPortAware service = (INeutronPortAware) instance;\r
-                int status = service.canUpdatePort(singleton, original);\r
-                if (status < 200 || status > 299)\r
-                    return Response.status(status).build();\r
-            }\r
-        }\r
-\r
-        // Verify the new fixed ips are valid\r
-        List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();\r
-        if (fixedIPs != null && fixedIPs.size() > 0) {\r
-            Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();\r
-            while (fixedIPIterator.hasNext()) {\r
-                Neutron_IPs ip = fixedIPIterator.next();\r
-                if (ip.getSubnetUUID() == null)\r
-                    return Response.status(400).build();\r
-                if (!subnetInterface.subnetExists(ip.getSubnetUUID()))\r
-                    return Response.status(400).build();\r
-                NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());\r
-                if (!target.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))\r
-                    return Response.status(400).build();\r
-                if (ip.getIpAddress() != null) {\r
-                    if (!subnet.isValidIP(ip.getIpAddress()))\r
-                        return Response.status(400).build();\r
-                    if (subnet.isIPInUse(ip.getIpAddress()))\r
-                        return Response.status(409).build();\r
-                }\r
-            }\r
-        }\r
-\r
-//        TODO: Support change of security groups\r
-        // update the port and return the modified object\r
-        portInterface.updatePort(portUUID, singleton);\r
-        NeutronPort updatedPort = portInterface.getPort(portUUID);\r
-        if (instances != null) {\r
-            for (Object instance : instances) {\r
-                INeutronPortAware service = (INeutronPortAware) instance;\r
-                service.neutronPortUpdated(updatedPort);\r
-            }\r
-        }\r
-        return Response.status(200).entity(\r
-                new NeutronPortRequest(updatedPort)).build();\r
-\r
-    }\r
-\r
-    /**\r
-     * Deletes a Port */\r
-\r
-    @Path("{portUUID}")\r
-    @DELETE\r
-    @StatusCodes({\r
-        @ResponseCode(code = 204, condition = "No Content"),\r
-        @ResponseCode(code = 401, condition = "Unauthorized"),\r
-        @ResponseCode(code = 403, condition = "Forbidden"),\r
-        @ResponseCode(code = 404, condition = "Not Found"),\r
-        @ResponseCode(code = 501, condition = "Not Implemented") })\r
-    public Response deletePort(\r
-            @PathParam("portUUID") String portUUID) {\r
-        INeutronPortCRUD portInterface = NeutronNBInterfaces.getIfNBPortCRUD("default",this);\r
-        if (portInterface == null) {\r
-            throw new ServiceUnavailableException("Port CRUD Interface "\r
-                    + RestMessages.SERVICEUNAVAILABLE.toString());\r
-        }\r
-\r
-        // port has to exist and not be owned by anyone.  then it can be removed from the cache\r
-        if (!portInterface.portExists(portUUID))\r
-            return Response.status(404).build();\r
-        NeutronPort port = portInterface.getPort(portUUID);\r
-        if (port.getDeviceID() != null ||\r
-                port.getDeviceOwner() != null)\r
-            Response.status(403).build();\r
-        NeutronPort singleton = portInterface.getPort(portUUID);\r
-        Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);\r
-        if (instances != null) {\r
-            for (Object instance : instances) {\r
-                INeutronPortAware service = (INeutronPortAware) instance;\r
-                int status = service.canDeletePort(singleton);\r
-                if (status < 200 || status > 299)\r
-                    return Response.status(status).build();\r
-            }\r
-        }\r
-        portInterface.removePort(portUUID);\r
-        if (instances != null) {\r
-            for (Object instance : instances) {\r
-                INeutronPortAware service = (INeutronPortAware) instance;\r
-                service.neutronPortDeleted(singleton);\r
-            }\r
-        }\r
-        return Response.status(204).build();\r
-    }\r
-}\r
+/*
+ * Copyright IBM Corporation, 2013.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.networkconfig.neutron.northbound;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.codehaus.enunciate.jaxrs.ResponseCode;
+import org.codehaus.enunciate.jaxrs.StatusCodes;
+import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronPortAware;
+import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
+import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
+import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
+import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;
+import org.opendaylight.controller.northbound.commons.RestMessages;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
+import org.opendaylight.controller.sal.utils.ServiceHelper;
+
+/**
+ * Neutron Northbound REST APIs.<br>
+ * This class provides REST APIs for managing neutron port objects
+ *
+ * <br>
+ * <br>
+ * Authentication scheme : <b>HTTP Basic</b><br>
+ * Authentication realm : <b>opendaylight</b><br>
+ * Transport : <b>HTTP and HTTPS</b><br>
+ * <br>
+ * HTTPS Authentication is disabled by default. Administrator can enable it in
+ * tomcat-server.xml after adding a proper keystore / SSL certificate from a
+ * trusted authority.<br>
+ * More info :
+ * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
+ *
+ */
+
+@Path("/ports")
+public class NeutronPortsNorthbound {
+
+    final String mac_regex="^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
+
+    private NeutronPort extractFields(NeutronPort o, List<String> fields) {
+        return o.extractFields(fields);
+    }
+
+    /**
+     * Returns a list of all Ports */
+
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    //@TypeHint(OpenStackPorts.class)
+    @StatusCodes({
+        @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "Unauthorized"),
+        @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response listPorts(
+            // return fields
+            @QueryParam("fields") List<String> fields,
+            // note: openstack isn't clear about filtering on lists, so we aren't handling them
+            @QueryParam("id") String queryID,
+            @QueryParam("network_id") String queryNetworkID,
+            @QueryParam("name") String queryName,
+            @QueryParam("admin_state_up") String queryAdminStateUp,
+            @QueryParam("status") String queryStatus,
+            @QueryParam("mac_address") String queryMACAddress,
+            @QueryParam("device_id") String queryDeviceID,
+            @QueryParam("device_owner") String queryDeviceOwner,
+            @QueryParam("tenant_id") String queryTenantID,
+            // pagination
+            @QueryParam("limit") String limit,
+            @QueryParam("marker") String marker,
+            @QueryParam("page_reverse") String pageReverse
+            // sorting not supported
+            ) {
+        INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
+        if (portInterface == null) {
+            throw new ServiceUnavailableException("Port CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        List<NeutronPort> allPorts = portInterface.getAllPorts();
+        List<NeutronPort> ans = new ArrayList<NeutronPort>();
+        Iterator<NeutronPort> i = allPorts.iterator();
+        while (i.hasNext()) {
+            NeutronPort oSS = i.next();
+            if ((queryID == null || queryID.equals(oSS.getID())) &&
+                    (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
+                    (queryName == null || queryName.equals(oSS.getName())) &&
+                    (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
+                    (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
+                    (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
+                    (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
+                    (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
+                    (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
+                if (fields.size() > 0) {
+                    ans.add(extractFields(oSS,fields));
+                } else {
+                    ans.add(oSS);
+                }
+            }
+        }
+        //TODO: apply pagination to results
+        return Response.status(200).entity(
+                new NeutronPortRequest(ans)).build();
+    }
+
+    /**
+     * Returns a specific Port */
+
+    @Path("{portUUID}")
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    //@TypeHint(OpenStackPorts.class)
+    @StatusCodes({
+        @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "Unauthorized"),
+        @ResponseCode(code = 404, condition = "Not Found"),
+        @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response showPort(
+            @PathParam("portUUID") String portUUID,
+            // return fields
+            @QueryParam("fields") List<String> fields ) {
+        INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
+        if (portInterface == null) {
+            throw new ServiceUnavailableException("Port CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (!portInterface.portExists(portUUID)) {
+            throw new ResourceNotFoundException("port UUID does not exist.");
+        }
+        if (fields.size() > 0) {
+            NeutronPort ans = portInterface.getPort(portUUID);
+            return Response.status(200).entity(
+                    new NeutronPortRequest(extractFields(ans, fields))).build();
+        } else {
+            return Response.status(200).entity(
+                    new NeutronPortRequest(portInterface.getPort(portUUID))).build();
+        }
+    }
+
+    /**
+     * Creates new Ports */
+
+    @POST
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    //@TypeHint(OpenStackPorts.class)
+    @StatusCodes({
+        @ResponseCode(code = 201, condition = "Created"),
+        @ResponseCode(code = 400, condition = "Bad Request"),
+        @ResponseCode(code = 401, condition = "Unauthorized"),
+        @ResponseCode(code = 403, condition = "Forbidden"),
+        @ResponseCode(code = 404, condition = "Not Found"),
+        @ResponseCode(code = 409, condition = "Conflict"),
+        @ResponseCode(code = 501, condition = "Not Implemented"),
+        @ResponseCode(code = 503, condition = "MAC generation failure") })
+    public Response createPorts(final NeutronPortRequest input) {
+        INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
+        if (portInterface == null) {
+            throw new ServiceUnavailableException("Port CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
+        if (networkInterface == null) {
+            throw new ServiceUnavailableException("Network CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
+        if (subnetInterface == null) {
+            throw new ServiceUnavailableException("Subnet CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (input.isSingleton()) {
+            NeutronPort singleton = input.getSingleton();
+
+            /*
+             * the port must be part of an existing network, must not already exist,
+             * have a valid MAC and the MAC not be in use
+             */
+            if (singleton.getNetworkUUID() == null) {
+                throw new BadRequestException("network UUID musy be specified");
+            }
+            if (portInterface.portExists(singleton.getID())) {
+                throw new BadRequestException("port UUID already exists");
+            }
+            if (!networkInterface.networkExists(singleton.getNetworkUUID())) {
+                throw new ResourceNotFoundException("network UUID does not exist.");
+            }
+            if (singleton.getMacAddress() == null ||
+                    !singleton.getMacAddress().matches(mac_regex)) {
+                throw new BadRequestException("MAC address not properly formatted");
+            }
+            if (portInterface.macInUse(singleton.getMacAddress())) {
+                throw new ResourceConflictException("MAC Address is in use.");
+            }
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronPortAware service = (INeutronPortAware) instance;
+                    int status = service.canCreatePort(singleton);
+                    if (status < 200 || status > 299) {
+                        return Response.status(status).build();
+                    }
+                }
+            }
+            /*
+             * if fixed IPs are specified, each one has to have an existing subnet ID
+             * that is in the same scoping network as the port.  In addition, if an IP
+             * address is specified it has to be a valid address for the subnet and not
+             * already in use
+             */
+            List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
+            if (fixedIPs != null && fixedIPs.size() > 0) {
+                Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
+                while (fixedIPIterator.hasNext()) {
+                    Neutron_IPs ip = fixedIPIterator.next();
+                    if (ip.getSubnetUUID() == null) {
+                        throw new BadRequestException("subnet UUID not specified");
+                    }
+                    if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
+                        throw new BadRequestException("subnet UUID must exists");
+                    }
+                    NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
+                    if (!singleton.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
+                        throw new BadRequestException("network UUID must match that of subnet");
+                    }
+                    if (ip.getIpAddress() != null) {
+                        if (!subnet.isValidIP(ip.getIpAddress())) {
+                            throw new BadRequestException("IP address is not valid");
+                        }
+                        if (subnet.isIPInUse(ip.getIpAddress())) {
+                            throw new ResourceConflictException("IP address is in use.");
+                        }
+                    }
+                }
+            }
+
+            // add the port to the cache
+            portInterface.addPort(singleton);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronPortAware service = (INeutronPortAware) instance;
+                    service.neutronPortCreated(singleton);
+                }
+            }
+        } else {
+            List<NeutronPort> bulk = input.getBulk();
+            Iterator<NeutronPort> i = bulk.iterator();
+            HashMap<String, NeutronPort> testMap = new HashMap<String, NeutronPort>();
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
+            while (i.hasNext()) {
+                NeutronPort test = i.next();
+
+                /*
+                 * the port must be part of an existing network, must not already exist,
+                 * have a valid MAC and the MAC not be in use.  Further the bulk request
+                 * can't already contain a new port with the same UUID
+                 */
+                if (portInterface.portExists(test.getID())) {
+                    throw new BadRequestException("port UUID already exists");
+                }
+                if (testMap.containsKey(test.getID())) {
+                    throw new BadRequestException("port UUID already exists");
+                }
+                for (NeutronPort check : testMap.values()) {
+                    if (test.getMacAddress().equalsIgnoreCase(check.getMacAddress())) {
+                        throw new ResourceConflictException("MAC address already allocated");
+                    }
+                    for (Neutron_IPs test_fixedIP : test.getFixedIPs()) {
+                        for (Neutron_IPs check_fixedIP : check.getFixedIPs()) {
+                            if (test_fixedIP.getIpAddress().equals(check_fixedIP.getIpAddress())) {
+                                throw new ResourceConflictException("IP address already allocated");
+                            }
+                        }
+                    }
+                }
+                testMap.put(test.getID(), test);
+                if (!networkInterface.networkExists(test.getNetworkUUID())) {
+                    throw new ResourceNotFoundException("network UUID does not exist.");
+                }
+                if (!test.getMacAddress().matches(mac_regex)) {
+                    throw new BadRequestException("MAC address not properly formatted");
+                }
+                if (portInterface.macInUse(test.getMacAddress())) {
+                    throw new ResourceConflictException("MAC address in use");
+                }
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronPortAware service = (INeutronPortAware) instance;
+                        int status = service.canCreatePort(test);
+                        if (status < 200 || status > 299) {
+                            return Response.status(status).build();
+                        }
+                    }
+                }
+                /*
+                 * if fixed IPs are specified, each one has to have an existing subnet ID
+                 * that is in the same scoping network as the port.  In addition, if an IP
+                 * address is specified it has to be a valid address for the subnet and not
+                 * already in use (or be the gateway IP address of the subnet)
+                 */
+                List<Neutron_IPs> fixedIPs = test.getFixedIPs();
+                if (fixedIPs != null && fixedIPs.size() > 0) {
+                    Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
+                    while (fixedIPIterator.hasNext()) {
+                        Neutron_IPs ip = fixedIPIterator.next();
+                        if (ip.getSubnetUUID() == null) {
+                            throw new BadRequestException("subnet UUID must be specified");
+                        }
+                        if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
+                            throw new BadRequestException("subnet UUID doesn't exists");
+                        }
+                        NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
+                        if (!test.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
+                            throw new BadRequestException("network UUID must match that of subnet");
+                        }
+                        if (ip.getIpAddress() != null) {
+                            if (!subnet.isValidIP(ip.getIpAddress())) {
+                                throw new BadRequestException("ip address not valid");
+                            }
+                            //TODO: need to add consideration for a fixed IP being assigned the same address as a allocated IP in the
+                            //same bulk create
+                            if (subnet.isIPInUse(ip.getIpAddress())) {
+                                throw new ResourceConflictException("IP address in use");
+                            }
+                        }
+                    }
+                }
+            }
+
+            //once everything has passed, then we can add to the cache
+            i = bulk.iterator();
+            while (i.hasNext()) {
+                NeutronPort test = i.next();
+                portInterface.addPort(test);
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronPortAware service = (INeutronPortAware) instance;
+                        service.neutronPortCreated(test);
+                    }
+                }
+            }
+        }
+        return Response.status(201).entity(input).build();
+    }
+
+    /**
+     * Updates a Port */
+
+    @Path("{portUUID}")
+    @PUT
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    //@TypeHint(OpenStackPorts.class)
+    @StatusCodes({
+        @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 400, condition = "Bad Request"),
+        @ResponseCode(code = 401, condition = "Unauthorized"),
+        @ResponseCode(code = 403, condition = "Forbidden"),
+        @ResponseCode(code = 404, condition = "Not Found"),
+        @ResponseCode(code = 409, condition = "Conflict"),
+        @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response updatePort(
+            @PathParam("portUUID") String portUUID,
+            NeutronPortRequest input
+            ) {
+        INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
+        if (portInterface == null) {
+            throw new ServiceUnavailableException("Port CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
+        if (subnetInterface == null) {
+            throw new ServiceUnavailableException("Subnet CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        // port has to exist and only a single delta is supported
+        if (!portInterface.portExists(portUUID)) {
+            throw new ResourceNotFoundException("port UUID does not exist.");
+        }
+        NeutronPort target = portInterface.getPort(portUUID);
+        if (!input.isSingleton()) {
+            throw new BadRequestException("only singleton edit suported");
+        }
+        NeutronPort singleton = input.getSingleton();
+        NeutronPort original = portInterface.getPort(portUUID);
+
+        // deltas restricted by Neutron
+        if (singleton.getID() != null || singleton.getTenantID() != null ||
+                singleton.getStatus() != null) {
+            throw new BadRequestException("attribute change blocked by Neutron");
+        }
+
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronPortAware service = (INeutronPortAware) instance;
+                int status = service.canUpdatePort(singleton, original);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        // Verify the new fixed ips are valid
+        List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
+        if (fixedIPs != null && fixedIPs.size() > 0) {
+            Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
+            while (fixedIPIterator.hasNext()) {
+                Neutron_IPs ip = fixedIPIterator.next();
+                if (ip.getSubnetUUID() == null) {
+                    throw new BadRequestException("subnet UUID must be specified");
+                }
+                if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
+                    throw new BadRequestException("subnet UUID doesn't exist.");
+                }
+                NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
+                if (!target.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
+                    throw new BadRequestException("network UUID must match that of subnet");
+                }
+                if (ip.getIpAddress() != null) {
+                    if (!subnet.isValidIP(ip.getIpAddress())) {
+                        throw new BadRequestException("invalid IP address");
+                    }
+                    if (subnet.isIPInUse(ip.getIpAddress())) {
+                        throw new ResourceConflictException("IP address in use");
+                    }
+                }
+            }
+        }
+
+        //        TODO: Support change of security groups
+        // update the port and return the modified object
+        portInterface.updatePort(portUUID, singleton);
+        NeutronPort updatedPort = portInterface.getPort(portUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronPortAware service = (INeutronPortAware) instance;
+                service.neutronPortUpdated(updatedPort);
+            }
+        }
+        return Response.status(200).entity(
+                new NeutronPortRequest(updatedPort)).build();
+
+    }
+
+    /**
+     * Deletes a Port */
+
+    @Path("{portUUID}")
+    @DELETE
+    @StatusCodes({
+        @ResponseCode(code = 204, condition = "No Content"),
+        @ResponseCode(code = 401, condition = "Unauthorized"),
+        @ResponseCode(code = 403, condition = "Forbidden"),
+        @ResponseCode(code = 404, condition = "Not Found"),
+        @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response deletePort(
+            @PathParam("portUUID") String portUUID) {
+        INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
+        if (portInterface == null) {
+            throw new ServiceUnavailableException("Port CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        // port has to exist and not be owned by anyone.  then it can be removed from the cache
+        if (!portInterface.portExists(portUUID)) {
+            throw new ResourceNotFoundException("port UUID does not exist.");
+        }
+        NeutronPort port = portInterface.getPort(portUUID);
+        if (port.getDeviceID() != null ||
+                port.getDeviceOwner() != null) {
+            Response.status(403).build();
+        }
+        NeutronPort singleton = portInterface.getPort(portUUID);
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronPortAware service = (INeutronPortAware) instance;
+                int status = service.canDeletePort(singleton);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+        portInterface.removePort(portUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronPortAware service = (INeutronPortAware) instance;
+                service.neutronPortDeleted(singleton);
+            }
+        }
+        return Response.status(204).build();
+    }
+}