Merge "Few debug enhancements to debug hashing issues"
authorAlessandro Boch <aboch@cisco.com>
Fri, 20 Sep 2013 17:19:47 +0000 (17:19 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 20 Sep 2013 17:19:47 +0000 (17:19 +0000)
19 files changed:
opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java
opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java
opendaylight/northbound/commons/pom.xml
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java
opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java
opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java
opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java [new file with mode: 0644]
opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java
opendaylight/web/devices/src/main/resources/js/page.js
opendaylight/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java
opendaylight/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java
opendaylight/web/troubleshoot/src/main/resources/js/page.js

index 488f8928de478ec8faab7122d93fd8f21cda0a62..2520172d8959a62f5a7fb2af37826c0a27a59dd9 100644 (file)
@@ -479,12 +479,12 @@ public class ContainerFlowConfig implements Serializable {
     }
 
     /**
-     * Returns the protocol
+     * Get the IP protocol value
      *
      * @return the protocol
      */
     public Short getProtoNum() {
-        return protocol == null ? IPProtocols.ANY.shortValue() : IPProtocols.getProtocolNumberShort(protocol);
+        return protocol == null ? null : IPProtocols.getProtocolNumberShort(protocol);
     }
 
     /**
@@ -578,16 +578,15 @@ public class ContainerFlowConfig implements Serializable {
 
     /**
      * Validate the protocol field. Either it can be a enum defined in IPProtocols.java
-     * or a value between 1 and 255
+     * or a valid IP proto value between 0 and 255, see:
+     * http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
+     * for more details.
      *
      * @return true if a valid protocol value
      */
     private boolean hasValidProtocol() {
-        if (protocol != null && !protocol.isEmpty()) {
-            short proto = this.getProtoNum();
-            return (((proto != 0) && (proto > 0) && (proto < 256)) || protocol.equalsIgnoreCase("any"));
-        }
-        return true;
+        IPProtocols p = IPProtocols.fromString(protocol);
+        return p != null;
     }
 
     /**
@@ -664,9 +663,8 @@ public class ContainerFlowConfig implements Serializable {
             mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address);
             match.setField(MatchType.NW_DST, ip, mask);
         }
-        if (this.protocol != null && !this.protocol.trim().isEmpty() && !this.protocol.equalsIgnoreCase("any")) {
-            match.setField(MatchType.NW_PROTO, IPProtocols
-                    .getProtocolNumberByte(this.protocol));
+        if (IPProtocols.fromString(this.protocol) != IPProtocols.ANY) {
+            match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(this.protocol));
         }
         if (this.tpSrc != null && !this.tpSrc.trim().isEmpty()) {
             match.setField(MatchType.TP_SRC, Integer.valueOf(tpSrc).shortValue());
index 62d6855e109f77ac97baf5107fb2c0efbcaa603e..e0b8e9a786878fe6af6b67dd04aeee52958118db 100644 (file)
@@ -656,11 +656,8 @@ public class FlowConfig implements Serializable {
     }
 
     public boolean isProtocolValid(String protocol) {
-        int protocol_number = IPProtocols.getProtocolNumberInt(protocol);
-        if (protocol_number < 1 || protocol_number > 255) {
-            return false;
-        }
-        return true;
+        IPProtocols proto = IPProtocols.fromString(protocol);
+        return (proto != null);
     }
 
     private Status conflictWithContainerFlow(IContainer container) {
@@ -1033,7 +1030,7 @@ public class FlowConfig implements Serializable {
             mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address);
             match.setField(MatchType.NW_DST, ip, mask);
         }
-        if (this.protocol != null) {
+        if (IPProtocols.fromString(this.protocol) != IPProtocols.ANY) {
             match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(this.protocol));
         }
         if (this.tosBits != null) {
index 6e3e6b6633b0fc6098ee6795dac661df71a20fed..c839d15f10c81308909a03f804e5587ec6ef612c 100644 (file)
@@ -202,59 +202,6 @@ public class ForwardingRulesManager implements
     private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
             new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
 
-    /*
-     * Create an executor pool to create the distributionOrder, this is a stop
-     * gap solution caused by an issue with non-transactional caches in the
-     * implementation we use, being currently worked on. It has been noticed in
-     * fact that when non-transactional caches are being used sometime the key
-     * are no distributed to all the nodes properly. To workaround the issue
-     * transactional caches are being used, but there was a reason for using
-     * non-transactional caches to start with, in fact we needed to be able in
-     * the context of a northbound transaction to program the FRM entries
-     * irrespective of the fact that transaction would commit or no else we
-     * would not be able to achieve the entry programming and implement the
-     * scheme for recovery from network element failures. Bottom line, now in
-     * order to make sure an update on a transactional cache goes out while in a
-     * transaction that need to be initiated by a different thread.
-     */
-    private ExecutorService executor;
-
-    class DistributeOrderCallable implements Callable<Future<Status>> {
-        private FlowEntryInstall e;
-        private FlowEntryInstall u;
-        private UpdateType t;
-        DistributeOrderCallable(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
-            this.e = e;
-            this.u = u;
-            this.t = t;
-        }
-
-        @Override
-        public Future<Status> call() throws Exception {
-            if (e == null || t == null) {
-                logsync.error("Unexpected null Entry up update type");
-                return null;
-            }
-            // Create the work order and distribute it
-            FlowEntryDistributionOrder fe =
-                    new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
-            // First create the monitor job
-            FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
-            logsync.trace("Node {} not local so sending fe {}", e.getNode(), fe);
-            workMonitor.put(fe, ret);
-            if (t.equals(UpdateType.CHANGED)) {
-                // Then distribute the work
-                workOrder.put(fe, u);
-            } else {
-                // Then distribute the work
-                workOrder.put(fe, e);
-            }
-            logsync.trace("WorkOrder requested");
-            // Now create an Handle to monitor the execution of the operation
-            return ret;
-        }
-    }
-
     /**
      * @param e
      *            Entry being installed/updated/removed
@@ -275,21 +222,23 @@ public class ForwardingRulesManager implements
 
         Node n = e.getNode();
         if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
-            Callable<Future<Status>> worker = new DistributeOrderCallable(e, u, t);
-            if (worker != null) {
-                Future<Future<Status>> workerRes = this.executor.submit(worker);
-                try {
-                    return workerRes.get();
-                } catch (InterruptedException e1) {
-                    // we where interrupted, not a big deal.
-                    return null;
-                } catch (ExecutionException e1) {
-                    logsync.error(
-                            "We got an execution exception {} we cannot much, so returning we don't have nothing to wait for",
-                            e);
-                    return null;
-                }
+            // Create the work order and distribute it
+            FlowEntryDistributionOrder fe =
+                    new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
+            // First create the monitor job
+            FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
+            logsync.trace("Node {} not local so sending fe {}", n, fe);
+            workMonitor.put(fe, ret);
+            if (t.equals(UpdateType.CHANGED)) {
+                // Then distribute the work
+                workOrder.put(fe, u);
+            } else {
+                // Then distribute the work
+                workOrder.put(fe, e);
             }
+            logsync.trace("WorkOrder requested");
+            // Now create an Handle to monitor the execution of the operation
+            return ret;
         }
 
         logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
@@ -1407,10 +1356,10 @@ public class ForwardingRulesManager implements
                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
 
             clusterContainerService.createCache(WORKSTATUSCACHE,
- EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
+ EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
 
             clusterContainerService.createCache(WORKORDERCACHE,
- EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
+ EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
 
         } catch (CacheConfigException cce) {
             log.error("CacheConfigException");
@@ -2112,6 +2061,7 @@ public class ForwardingRulesManager implements
      *      pratice to have in it's context operations that can take time,
      *      hence moving off to a different thread for async processing.
      */
+    private ExecutorService executor;
     @Override
     public void modeChangeNotify(final Node node, final boolean proactive) {
         Callable<Status> modeChangeCallable = new Callable<Status>() {
index 972bece91fd2ce9e0400bf2500397e76a2d19691..ff40ba07ee14c4dc5daf6c8ecb8c4d952fa839f3 100644 (file)
               javax.xml.bind.annotation,
               org.objectweb.asm,
               org.opendaylight.controller.sal.utils,
+              org.opendaylight.controller.sal.core,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.containermanager,
               org.opendaylight.controller.usermanager,
+              org.opendaylight.controller.switchmanager,
               org.opendaylight.controller.northbound.bundlescanner,
               org.osgi.framework,
               org.osgi.service.packageadmin,
     </plugins>
   </build>
   <dependencies>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>switchmanager</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
       <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>sal</artifactId>
index 9f47e0c9718f542f49d6bea3079045c482359230..bf8844d9f61d808d4983b2c22585ceecab234c72 100644 (file)
@@ -8,10 +8,15 @@ import javax.ws.rs.core.Response;
 import org.opendaylight.controller.containermanager.IContainerAuthorization;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.opendaylight.controller.sal.core.Description;
+import org.opendaylight.controller.sal.core.Name;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
+import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.usermanager.IUserManager;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -136,4 +141,55 @@ public class NorthboundUtils {
     public static void auditlog(String moduleName, String user, String action, String resource) {
         auditlog(moduleName, user, action, resource, null);
     }
+
+    public static String getNodeDesc(Node node, ISwitchManager switchManager) {
+        Description desc = (Description) switchManager.getNodeProp(node,
+                Description.propertyName);
+        String description = (desc == null) ? "" : desc.getValue();
+        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node
+                .toString() : description;
+    }
+
+    public static String getNodeDesc(Node node, String containerName,
+            Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class, containerName, bundle);
+        if (switchManager == null) {
+            return null;
+        }
+
+        return getNodeDesc(node, switchManager);
+    }
+
+    public static String getNodeDesc(Node node, Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class,
+                        GlobalConstants.DEFAULT.toString(), bundle);
+        if (switchManager == null) {
+            return null;
+        }
+
+        return getNodeDesc(node, switchManager);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector,
+            String container, Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class, container, bundle);
+        return getPortName(nodeConnector, switchManager);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector, Object bundle) {
+        return getPortName(nodeConnector, GlobalConstants.DEFAULT.toString(), bundle);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector,
+            ISwitchManager switchManager) {
+        Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
+                Name.NamePropName));
+        String nodeConnectorName = (ncName != null) ? ncName.getValue() : nodeConnector.getNodeConnectorIdAsString();
+        nodeConnectorName = nodeConnectorName + "@"
+                + getNodeDesc(nodeConnector.getNode(), switchManager);
+        return nodeConnectorName.substring(0, nodeConnectorName.length());
+    }
 }
index ea3f748dcc02e820c6b88aab5f2a10a73fef0cdf..1e88c4430548f6de805ee67c4441f49e6db89f3c 100644 (file)
@@ -23,7 +23,6 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
-import javax.xml.bind.JAXBElement;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -66,20 +65,20 @@ public class FlowProgrammerNorthbound {
 
     @Context
     public void setSecurityContext(SecurityContext context) {
-        if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+        if (context != null && context.getUserPrincipal() != null) {
+            username = context.getUserPrincipal().getName();
+        }
     }
 
     protected String getUserName() {
         return username;
     }
 
-    private IForwardingRulesManager getForwardingRulesManagerService(
-            String containerName) {
-        IContainerManager containerManager = (IContainerManager) ServiceHelper
-                .getGlobalInstance(IContainerManager.class, this);
+    private IForwardingRulesManager getForwardingRulesManagerService(String containerName) {
+        IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
+                IContainerManager.class, this);
         if (containerManager == null) {
-            throw new ServiceUnavailableException("Container "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         boolean found = false;
@@ -91,28 +90,24 @@ public class FlowProgrammerNorthbound {
         }
 
         if (found == false) {
-            throw new ResourceNotFoundException(containerName + " "
-                    + RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString());
         }
 
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         return frm;
     }
 
-    private List<FlowConfig> getStaticFlowsInternal(String containerName,
-            Node node) {
+    private List<FlowConfig> getStaticFlowsInternal(String containerName, Node node) {
         IForwardingRulesManager frm = getForwardingRulesManagerService(containerName);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         List<FlowConfig> flows = new ArrayList<FlowConfig>();
@@ -122,17 +117,14 @@ public class FlowProgrammerNorthbound {
                 flows.add(flow);
             }
         } else {
-            ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
-                    ISwitchManager.class, containerName, this);
+            ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
 
             if (sm == null) {
-                throw new ServiceUnavailableException("Switch Manager "
-                        + RestMessages.SERVICEUNAVAILABLE.toString());
+                throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
             }
 
             if (!sm.getNodes().contains(node)) {
-                throw new ResourceNotFoundException(node.toString() + " : "
-                        + RestMessages.NONODE.toString());
+                throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString());
             }
 
             for (FlowConfig flow : frm.getStaticFlows(node)) {
@@ -149,7 +141,7 @@ public class FlowProgrammerNorthbound {
      *            Name of the Container (Eg. 'default')
      * @return List of flows configured on a given container
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -184,22 +176,17 @@ public class FlowProgrammerNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(FlowConfigs.class)
-    @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public FlowConfigs getStaticFlows(
-            @PathParam("containerName") String containerName) {
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
-        }
-
-        List<FlowConfig> flowConfigs = getStaticFlowsInternal(containerName,
-                null);
+    @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName) {
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
+        }
+
+        List<FlowConfig> flowConfigs = getStaticFlowsInternal(containerName, null);
         return new FlowConfigs(flowConfigs);
     }
 
@@ -214,7 +201,7 @@ public class FlowProgrammerNorthbound {
      *            Node Identifier (Eg. '00:00:00:00:00:00:00:01')
      * @return List of flows configured on a Node in a container
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -249,25 +236,19 @@ public class FlowProgrammerNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(FlowConfigs.class)
-    @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName or nodeId is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public FlowConfigs getStaticFlows(
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId) {
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+    @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName or nodeId is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) {
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         Node node = Node.fromString(nodeType, nodeId);
         if (node == null) {
-            throw new ResourceNotFoundException(nodeId + " : "
-                    + RestMessages.NONODE.toString());
+            throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
         }
         List<FlowConfig> flows = getStaticFlowsInternal(containerName, node);
         return new FlowConfigs(flows);
@@ -287,7 +268,7 @@ public class FlowProgrammerNorthbound {
      *            Human-readable name for the configured flow (Eg. 'Flow1')
      * @return Flow configuration matching the name and nodeId on a Container
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -320,26 +301,20 @@ public class FlowProgrammerNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(FlowConfig.class)
-    @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName or NodeId or Configuration name is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public FlowConfig getStaticFlow(
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId, @PathParam("name") String name) {
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+    @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName or NodeId or Configuration name is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    public FlowConfig getStaticFlow(@PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, @PathParam("name") String name) {
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         IForwardingRulesManager frm = getForwardingRulesManagerService(containerName);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         Node node = handleNodeAvailability(containerName, nodeType, nodeId);
@@ -353,8 +328,8 @@ public class FlowProgrammerNorthbound {
     }
 
     /**
-     * Add a flow configuration. If a flow by the given name already
-     * exists, this method will respond with a non-successful status response.
+     * Add a flow configuration. If a flow by the given name already exists,
+     * this method will respond with a non-successful status response.
      *
      * @param containerName
      *            Name of the Container (Eg. 'default')
@@ -368,7 +343,7 @@ public class FlowProgrammerNorthbound {
      *            Flow Configuration in JSON or XML format
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -401,26 +376,21 @@ public class FlowProgrammerNorthbound {
     @PUT
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({
-            @ResponseCode(code = 201, condition = "Flow Config processed successfully"),
-            @ResponseCode(code = 400, condition = "Failed to create Static Flow entry due to invalid flow configuration"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or nodeId is not found"),
-            @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"),
-            @ResponseCode(code = 409, condition = "Failed to create Static Flow entry due to Conflicting Name or configuration"),
-            @ResponseCode(code = 500, condition = "Failed to create Static Flow entry. Failure Reason included in HTTP Error response"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response addFlow(
-            @PathParam(value = "containerName") String containerName,
-            @PathParam(value = "name") String name,
-            @PathParam("nodeType") String nodeType,
-            @PathParam(value = "nodeId") String nodeId,
-            @TypeHint(FlowConfig.class) FlowConfig flowConfig) {
-
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        @ResponseCode(code = 201, condition = "Flow Config processed successfully"),
+        @ResponseCode(code = 400, condition = "Failed to create Static Flow entry due to invalid flow configuration"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or nodeId is not found"),
+        @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"),
+        @ResponseCode(code = 409, condition = "Failed to create Static Flow entry due to Conflicting Name or configuration"),
+        @ResponseCode(code = 500, condition = "Failed to create Static Flow entry. Failure Reason included in HTTP Error response"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response addFlow(@PathParam(value = "containerName") String containerName,
+            @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType,
+            @PathParam(value = "nodeId") String nodeId, @TypeHint(FlowConfig.class) FlowConfig flowConfig) {
+
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         if (flowConfig.getNode() == null) {
@@ -434,22 +404,21 @@ public class FlowProgrammerNorthbound {
         IForwardingRulesManager frm = getForwardingRulesManagerService(containerName);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         Node node = handleNodeAvailability(containerName, nodeType, nodeId);
 
         FlowConfig staticFlow = frm.getStaticFlow(name, node);
         if (staticFlow != null) {
-            throw new ResourceConflictException(name + " already exists."
-                    + RestMessages.RESOURCECONFLICT.toString());
+            throw new ResourceConflictException(name + " already exists." + RestMessages.RESOURCECONFLICT.toString());
         }
 
         Status status = frm.addStaticFlow(flowConfig);
 
         if (status.isSuccess()) {
-            NorthboundUtils.auditlog("Flow", username, "added", name, containerName);
+            NorthboundUtils.auditlog("Flow Entry", username, "added",
+                    name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName);
             return Response.status(Response.Status.CREATED).entity("Success").build();
         }
         return NorthboundUtils.getResponse(status);
@@ -468,7 +437,7 @@ public class FlowProgrammerNorthbound {
      *            Name of the Static Flow configuration (Eg. 'Flow1')
      * @return Response as dictated by the HTTP Response code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -482,44 +451,39 @@ public class FlowProgrammerNorthbound {
     @DELETE
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({
-            @ResponseCode(code = 204, condition = "Flow Config deleted successfully"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"),
-            @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"),
-            @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"),
-            @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
-    public Response deleteFlow(
-            @PathParam(value = "containerName") String containerName,
-            @PathParam(value = "name") String name,
-            @PathParam("nodeType") String nodeType,
+        @ResponseCode(code = 204, condition = "Flow Config deleted successfully"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"),
+        @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"),
+        @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"),
+        @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
+    public Response deleteFlow(@PathParam(value = "containerName") String containerName,
+            @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType,
             @PathParam(value = "nodeId") String nodeId) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         handleDefaultDisabled(containerName);
 
         IForwardingRulesManager frm = getForwardingRulesManagerService(containerName);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         Node node = handleNodeAvailability(containerName, nodeType, nodeId);
 
         FlowConfig staticFlow = frm.getStaticFlow(name, node);
         if (staticFlow == null) {
-            throw new ResourceNotFoundException(name + " : "
-                    + RestMessages.NOFLOW.toString());
+            throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString());
         }
 
         Status status = frm.removeStaticFlow(name, node);
         if (status.isSuccess()) {
-            NorthboundUtils.auditlog("Flow", username, "removed", name, containerName);
+            NorthboundUtils.auditlog("Flow Entry", username, "removed",
+                    name + " from Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName);
             return Response.noContent().build();
         }
         return NorthboundUtils.getResponse(status);
@@ -538,7 +502,7 @@ public class FlowProgrammerNorthbound {
      *            Name of the Static Flow configuration (Eg. 'Flow1')
      * @return Response as dictated by the HTTP Response code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -551,23 +515,19 @@ public class FlowProgrammerNorthbound {
     @POST
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({
-            @ResponseCode(code = 200, condition = "Flow Config processed successfully"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"),
-            @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"),
-            @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"),
-            @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
-    public Response toggleFlow(
-            @PathParam(value = "containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam(value = "nodeId") String nodeId,
+        @ResponseCode(code = 200, condition = "Flow Config processed successfully"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"),
+        @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"),
+        @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"),
+        @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
+    public Response toggleFlow(@PathParam(value = "containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId,
             @PathParam(value = "name") String name) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         handleDefaultDisabled(containerName);
@@ -575,60 +535,51 @@ public class FlowProgrammerNorthbound {
         IForwardingRulesManager frm = getForwardingRulesManagerService(containerName);
 
         if (frm == null) {
-            throw new ServiceUnavailableException("Flow Programmer "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         Node node = handleNodeAvailability(containerName, nodeType, nodeId);
 
         FlowConfig staticFlow = frm.getStaticFlow(name, node);
         if (staticFlow == null) {
-            throw new ResourceNotFoundException(name + " : "
-                    + RestMessages.NOFLOW.toString());
+            throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString());
         }
 
         Status status = frm.toggleStaticFlowStatus(staticFlow);
         if (status.isSuccess()) {
-            NorthboundUtils.auditlog("Flow", username, "toggled", name, containerName);
+            NorthboundUtils.auditlog("Flow Entry", username, "toggled",
+                    name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName);
         }
         return NorthboundUtils.getResponse(status);
     }
 
-    private Node handleNodeAvailability(String containerName, String nodeType,
-            String nodeId) {
+    private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
 
         Node node = Node.fromString(nodeType, nodeId);
         if (node == null) {
-            throw new ResourceNotFoundException(nodeId + " : "
-                    + RestMessages.NONODE.toString());
+            throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
         }
 
-        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
-                ISwitchManager.class, containerName, this);
+        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
 
         if (sm == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         if (!sm.getNodes().contains(node)) {
-            throw new ResourceNotFoundException(node.toString() + " : "
-                    + RestMessages.NONODE.toString());
+            throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString());
         }
         return node;
     }
 
     private void handleDefaultDisabled(String containerName) {
-        IContainerManager containerManager = (IContainerManager) ServiceHelper
-                .getGlobalInstance(IContainerManager.class, this);
+        IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
+                IContainerManager.class, this);
         if (containerManager == null) {
-            throw new InternalServerErrorException(
-                    RestMessages.INTERNALERROR.toString());
+            throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString());
         }
-        if (containerName.equals(GlobalConstants.DEFAULT.toString())
-                && containerManager.hasNonDefaultContainer()) {
-            throw new NotAcceptableException(
-                    RestMessages.DEFAULTDISABLED.toString());
+        if (containerName.equals(GlobalConstants.DEFAULT.toString()) && containerManager.hasNonDefaultContainer()) {
+            throw new NotAcceptableException(RestMessages.DEFAULTDISABLED.toString());
         }
     }
 
index 18d8e531143f66aceb1ab93b6f535112432175f3..eb91206bfcdf9bfdf151010e51e54961a43f4f7e 100644 (file)
@@ -7,7 +7,10 @@
  */
 package org.opendaylight.controller.subnets.northbound;
 
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
+
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
@@ -34,6 +37,7 @@ import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailab
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.switchmanager.ISwitchManager;
@@ -141,8 +145,8 @@ public class SubnetsNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName passed was not found"),
-            @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 404, condition = "The containerName passed was not found"),
+        @ResponseCode(code = 503, condition = "Service unavailable") })
     @TypeHint(SubnetConfigs.class)
     public SubnetConfigs listSubnets(@PathParam("containerName") String containerName) {
 
@@ -151,7 +155,8 @@ public class SubnetsNorthbound {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
         }
-         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
@@ -193,8 +198,8 @@ public class SubnetsNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName or subnetName passed was not found"),
-            @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 404, condition = "The containerName or subnetName passed was not found"),
+        @ResponseCode(code = 503, condition = "Service unavailable") })
     @TypeHint(SubnetConfig.class)
     public SubnetConfig listSubnet(@PathParam("containerName") String containerName,
             @PathParam("subnetName") String subnetName) {
@@ -205,7 +210,8 @@ public class SubnetsNorthbound {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
         }
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
@@ -217,10 +223,12 @@ public class SubnetsNorthbound {
     }
 
     /**
-     * Add a subnet into the specified container context, node connectors are optional
+     * Add a subnet into the specified container context, node connectors are
+     * optional
      *
      * @param containerName
-     *            name of the container context in which the subnet needs to be added
+     *            name of the container context in which the subnet needs to be
+     *            added
      * @param subnetName
      *            name of new subnet to be added
      * @param subnetConfigData
@@ -253,15 +261,14 @@ public class SubnetsNorthbound {
     @Path("/{containerName}/subnet/{subnetName}")
     @PUT
     @StatusCodes({ @ResponseCode(code = 201, condition = "Subnet created successfully"),
-            @ResponseCode(code = 400, condition = "Invalid data passed"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"),
-            @ResponseCode(code = 404, condition = "Container name passed was not found or subnet config is null"),
-            @ResponseCode(code = 500, condition = "Internal Server Error: Addition of subnet failed"),
-            @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 400, condition = "Invalid data passed"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"),
+        @ResponseCode(code = 404, condition = "Container name passed was not found or subnet config is null"),
+        @ResponseCode(code = 500, condition = "Internal Server Error: Addition of subnet failed"),
+        @ResponseCode(code = 503, condition = "Service unavailable") })
     public Response addSubnet(@PathParam("containerName") String containerName,
-            @PathParam("subnetName") String subnetName,
-            @TypeHint(SubnetConfig.class) SubnetConfig subnetConfigData) {
+            @PathParam("subnetName") String subnetName, @TypeHint(SubnetConfig.class) SubnetConfig subnetConfigData) {
 
         handleContainerDoesNotExist(containerName);
 
@@ -272,13 +279,21 @@ public class SubnetsNorthbound {
         SubnetConfig cfgObject = subnetConfigData;
         handleNameMismatch(cfgObject.getName(), subnetName);
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
         Status status = switchManager.addSubnet(cfgObject);
         if (status.isSuccess()) {
             NorthboundUtils.auditlog("Subnet Gateway", username, "added", subnetName, containerName);
+            if (subnetConfigData.getNodeConnectors() != null) {
+                for (NodeConnector port : subnetConfigData.getNodeConnectors()) {
+                    NorthboundUtils.auditlog("Port", getUserName(), "added",
+                            NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway " + subnetName,
+                            containerName);
+                }
+            }
             return Response.status(Response.Status.CREATED).build();
         }
         return NorthboundUtils.getResponse(status);
@@ -302,10 +317,10 @@ public class SubnetsNorthbound {
     @Path("/{containerName}/subnet/{subnetName}")
     @DELETE
     @StatusCodes({ @ResponseCode(code = 204, condition = "No Content"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName passed was not found"),
-            @ResponseCode(code = 500, condition = "Internal Server Error : Removal of subnet failed"),
-            @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName passed was not found"),
+        @ResponseCode(code = 500, condition = "Internal Server Error : Removal of subnet failed"),
+        @ResponseCode(code = 503, condition = "Service unavailable") })
     public Response removeSubnet(@PathParam("containerName") String containerName,
             @PathParam("subnetName") String subnetName) {
 
@@ -316,7 +331,8 @@ public class SubnetsNorthbound {
                     + containerName);
         }
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
@@ -367,11 +383,11 @@ public class SubnetsNorthbound {
     @POST
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({ @ResponseCode(code = 200, condition = "Configuration replaced successfully"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"),
-            @ResponseCode(code = 404, condition = "The containerName or subnetName is not found"),
-            @ResponseCode(code = 500, condition = "Internal server error: Modify subnet failed"),
-            @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"),
+        @ResponseCode(code = 404, condition = "The containerName or subnetName is not found"),
+        @ResponseCode(code = 500, condition = "Internal server error: Modify subnet failed"),
+        @ResponseCode(code = 503, condition = "Service unavailable") })
     public Response modifySubnet(@Context UriInfo uriInfo, @PathParam("containerName") String containerName,
             @PathParam("subnetName") String subnetName, @TypeHint(SubnetConfig.class) SubnetConfig subnetConfigData) {
 
@@ -396,10 +412,38 @@ public class SubnetsNorthbound {
 
         if (status.isSuccess()) {
             if (existingConf == null) {
-                NorthboundUtils.auditlog("Subnet Gateway", username, "created", subnetName, containerName);
+                NorthboundUtils.auditlog("Subnet Gateway", username, "added", subnetName, containerName);
+                if (subnetConfigData.getNodeConnectors() != null) {
+                    for (NodeConnector port : subnetConfigData.getNodeConnectors()) {
+                        NorthboundUtils.auditlog("Port", getUserName(), "added",
+                                NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway" + subnetName,
+                                containerName);
+                    }
+                }
                 return Response.created(uriInfo.getRequestUri()).build();
             } else {
-                NorthboundUtils.auditlog("Subnet Gateway", username, "modified", subnetName, containerName);
+                Set<NodeConnector> existingNCList = existingConf.getNodeConnectors();
+
+                if (existingNCList == null) {
+                    existingNCList = new HashSet<NodeConnector>(0);
+                }
+                if (subnetConfigData.getNodeConnectors() != null) {
+                    for (NodeConnector port : subnetConfigData.getNodeConnectors()) {
+                        if (!existingNCList.contains(port)) {
+                            NorthboundUtils.auditlog("Port", getUserName(), "added",
+                                    NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway "
+                                            + subnetName, containerName);
+                        }
+                    }
+                }
+                for (NodeConnector port : existingNCList) {
+                    if (!subnetConfigData.getNodeConnectors().contains(port)) {
+                        NorthboundUtils
+                                .auditlog("Port", getUserName(), "removed",
+                                        NorthboundUtils.getPortName(port, switchManager) + " from Subnet Gateway "
+                                                + subnetName, containerName);
+                    }
+                }
             }
         }
         return NorthboundUtils.getResponse(status);
index d88f9efa66ba66efc90fd8f3066cab26add96ccf..1777f1a8edcfc0f991acd65ccce6bda77b673ae3 100644 (file)
@@ -73,11 +73,10 @@ public class SwitchNorthbound {
     }
 
     private ISwitchManager getIfSwitchManagerService(String containerName) {
-        IContainerManager containerManager = (IContainerManager) ServiceHelper
-                .getGlobalInstance(IContainerManager.class, this);
+        IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
+                IContainerManager.class, this);
         if (containerManager == null) {
-            throw new ServiceUnavailableException("Container "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         boolean found = false;
@@ -90,16 +89,14 @@ public class SwitchNorthbound {
         }
 
         if (found == false) {
-            throw new ResourceNotFoundException(containerName + " "
-                    + RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString());
         }
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
 
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         return switchManager;
@@ -116,7 +113,7 @@ public class SwitchNorthbound {
      *         {@link org.opendaylight.controller.sal.core.Property} attached to
      *         it.
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -169,28 +166,24 @@ public class SwitchNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(Nodes.class)
-    @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public Nodes getNodes(@PathParam("containerName") String containerName) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         List<NodeProperties> res = new ArrayList<NodeProperties>();
@@ -251,34 +244,27 @@ public class SwitchNorthbound {
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(Response.class)
     @StatusCodes({
-            @ResponseCode(code = 201, condition = "Operation successful"),
-            @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or node or configuration name is not found"),
-            @ResponseCode(code = 406, condition = "The property cannot be configured in non-default container"),
-            @ResponseCode(code = 409, condition = "Unable to update configuration due to cluster conflict or conflicting description property"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response addNodeProperty(
-            @Context UriInfo uriInfo,
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId,
-            @PathParam("propertyName") String propertyName,
-            @PathParam("propertyValue") String propertyValue) {
+        @ResponseCode(code = 201, condition = "Operation successful"),
+        @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or node or configuration name is not found"),
+        @ResponseCode(code = 406, condition = "The property cannot be configured in non-default container"),
+        @ResponseCode(code = 409, condition = "Unable to update configuration due to cluster conflict or conflicting description property"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response addNodeProperty(@Context UriInfo uriInfo, @PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
+            @PathParam("propertyName") String propertyName, @PathParam("propertyValue") String propertyValue) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
@@ -294,6 +280,9 @@ public class SwitchNorthbound {
         SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties);
         Status status = switchManager.updateNodeConfig(newSwitchConfig);
         if (status.isSuccess()) {
+            NorthboundUtils.auditlog("Property " + propertyName, username, "updated",
+                    "of Node " + NorthboundUtils.getNodeDesc(node, switchManager), containerName);
+
             return Response.created(uriInfo.getRequestUri()).build();
         }
         return NorthboundUtils.getResponse(status);
@@ -308,14 +297,14 @@ public class SwitchNorthbound {
      *            Type of the node being programmed (Eg. 'OF')
      * @param nodeId
      *            Node Identifier as specified by
-     *            {@link org.opendaylight.controller.sal.core.Node}
-     *            (Eg. '00:00:00:00:00:03:01:02')
+     *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
+     *            '00:00:00:00:00:03:01:02')
      * @param propertyName
      *            Name of the Property. Properties that can be deleted are
      *            description, forwarding(only in default container) and tier.
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -328,32 +317,26 @@ public class SwitchNorthbound {
     @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}")
     @DELETE
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-    @StatusCodes({
-            @ResponseCode(code = 204, condition = "Property removed successfully"),
-            @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
-            @ResponseCode(code = 409, condition = "Unable to delete property due to cluster conflict"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response deleteNodeProperty(
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId,
+    @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"),
+        @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
+        @ResponseCode(code = 409, condition = "Unable to delete property due to cluster conflict"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response deleteNodeProperty(@PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
             @PathParam("propertyName") String propertyName) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
@@ -372,8 +355,9 @@ public class SwitchNorthbound {
                 nodeProperties.remove(propertyName.toLowerCase());
                 SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties);
                 status = switchManager.updateNodeConfig(newSwitchConfig);
-                if(status.isSuccess()){
-                    NorthboundUtils.auditlog("Node Property", username, "removed", propertyName  + " from " + nodeId, containerName);
+                if (status.isSuccess()) {
+                    NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node "
+                            + NorthboundUtils.getNodeDesc(node, switchManager), containerName);
                     return Response.noContent().build();
                 }
             }
@@ -401,7 +385,7 @@ public class SwitchNorthbound {
      *         {@link org.opendaylight.controller.sal.core.Property} attached to
      *         it.
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -444,30 +428,24 @@ public class SwitchNorthbound {
     @GET
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(NodeConnectors.class)
-    @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public NodeConnectors getNodeConnectors(
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId) {
+    @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    public NodeConnectors getNodeConnectors(@PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
@@ -479,14 +457,12 @@ public class SwitchNorthbound {
         }
 
         for (NodeConnector nc : ncs) {
-            Map<String, Property> propMap = switchManager
-                    .getNodeConnectorProps(nc);
+            Map<String, Property> propMap = switchManager.getNodeConnectorProps(nc);
             if (propMap == null) {
                 continue;
             }
             Set<Property> props = new HashSet<Property>(propMap.values());
-            NodeConnectorProperties ncProps = new NodeConnectorProperties(nc,
-                    props);
+            NodeConnectorProperties ncProps = new NodeConnectorProperties(nc, props);
             res.add(ncProps);
         }
 
@@ -504,8 +480,8 @@ public class SwitchNorthbound {
      *            Type of the node being programmed (Eg. 'OF')
      * @param nodeId
      *            Node Identifier as specified by
-     *            {@link org.opendaylight.controller.sal.core.Node}
-     *            (Eg. '00:00:00:00:00:00:00:03')
+     *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
+     *            '00:00:00:00:00:00:00:03')
      * @param nodeConnectorType
      *            Type of the node connector being programmed (Eg. 'OF')
      * @param nodeConnectorId
@@ -515,15 +491,14 @@ public class SwitchNorthbound {
      * @param propertyName
      *            Name of the Property specified by
      *            {@link org.opendaylight.controller.sal.core.Property} and its
-     *            extended classes
-     *            Property that can be configured is bandwidth
+     *            extended classes Property that can be configured is bandwidth
      * @param propertyValue
      *            Value of the Property specified by
      *            {@link org.opendaylight.controller.sal.core.Property} and its
      *            extended classes
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -536,54 +511,45 @@ public class SwitchNorthbound {
     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}/{propertyValue}")
     @PUT
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-    @StatusCodes({
-            @ResponseCode(code = 201, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
-            @ResponseCode(code = 409, condition = "Unable to add property due to cluster conflict"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response addNodeConnectorProperty(
-            @Context UriInfo uriInfo,
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId,
-            @PathParam("nodeConnectorType") String nodeConnectorType,
-            @PathParam("nodeConnectorId") String nodeConnectorId,
-            @PathParam("propertyName") String propertyName,
+    @StatusCodes({ @ResponseCode(code = 201, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
+        @ResponseCode(code = 409, condition = "Unable to add property due to cluster conflict"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response addNodeConnectorProperty(@Context UriInfo uriInfo,
+            @PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType,
+            @PathParam("nodeId") String nodeId, @PathParam("nodeConnectorType") String nodeConnectorType,
+            @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName,
             @PathParam("propertyValue") String propertyValue) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
         Node node = Node.fromString(nodeType, nodeId);
 
-        handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
-                nodeConnectorId);
-        NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
+        handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
+        NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
 
         Property prop = switchManager.createProperty(propertyName, propertyValue);
         if (prop == null) {
-            throw new ResourceNotFoundException(
-                    RestMessages.INVALIDDATA.toString());
+            throw new ResourceNotFoundException(RestMessages.INVALIDDATA.toString());
         }
 
         Status ret = switchManager.addNodeConnectorProp(nc, prop);
         if (ret.isSuccess()) {
+            NorthboundUtils.auditlog("Property " + propertyName, username, "updated", "of Node Connector "
+                    + NorthboundUtils.getPortName(nc, switchManager), containerName);
             return Response.created(uriInfo.getRequestUri()).build();
         }
         throw new InternalServerErrorException(ret.getDescription());
@@ -598,8 +564,8 @@ public class SwitchNorthbound {
      *            Type of the node being programmed (Eg. 'OF')
      * @param nodeId
      *            Node Identifier as specified by
-     *            {@link org.opendaylight.controller.sal.core.Node}
-     *            (Eg. '00:00:00:00:00:00:00:01')
+     *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
+     *            '00:00:00:00:00:00:00:01')
      * @param nodeConnectorType
      *            Type of the node connector being programmed (Eg. 'OF')
      * @param nodeConnectorId
@@ -612,7 +578,7 @@ public class SwitchNorthbound {
      *            extended classes. Property that can be deleted is bandwidth
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -625,45 +591,37 @@ public class SwitchNorthbound {
     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}")
     @DELETE
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-    @StatusCodes({
-            @ResponseCode(code = 204, condition = "Property removed successfully"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response deleteNodeConnectorProperty(
-            @PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType,
-            @PathParam("nodeId") String nodeId,
+    @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response deleteNodeConnectorProperty(@PathParam("containerName") String containerName,
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
             @PathParam("nodeConnectorType") String nodeConnectorType,
-            @PathParam("nodeConnectorId") String nodeConnectorId,
-            @PathParam("propertyName") String propertyName) {
+            @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
 
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
         Node node = Node.fromString(nodeType, nodeId);
 
-        handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
-                nodeConnectorId);
-        NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
+        handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
+        NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
         Status ret = switchManager.removeNodeConnectorProp(nc, propertyName);
         if (ret.isSuccess()) {
-            NorthboundUtils.auditlog("Node Connector Property", username, "removed", nc + " from " + nodeConnectorId, containerName);
+            NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node Connector "
+                    + NorthboundUtils.getPortName(nc, switchManager), containerName);
             return Response.noContent().build();
         }
         throw new ResourceNotFoundException(ret.getDescription());
@@ -676,7 +634,7 @@ public class SwitchNorthbound {
      *            Name of the Container (Eg. 'default')
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -689,27 +647,23 @@ public class SwitchNorthbound {
     @POST
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({
-            @ResponseCode(code = 200, condition = "Operation successful"),
-            @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
-            @ResponseCode(code = 404, condition = "The containerName is not found"),
-            @ResponseCode(code = 500, condition = "Failed to save switch configuration. Failure Reason included in HTTP Error response"),
-            @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public Response saveSwitchConfig(
-            @PathParam("containerName") String containerName) {
+        @ResponseCode(code = 200, condition = "Operation successful"),
+        @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
+        @ResponseCode(code = 404, condition = "The containerName is not found"),
+        @ResponseCode(code = 500, condition = "Failed to save switch configuration. Failure Reason included in HTTP Error response"),
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+    public Response saveSwitchConfig(@PathParam("containerName") String containerName) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
         }
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
         if (switchManager == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         Status ret = switchManager.saveSwitchConfig();
@@ -719,51 +673,41 @@ public class SwitchNorthbound {
         throw new InternalServerErrorException(ret.getDescription());
     }
 
-    private Node handleNodeAvailability(String containerName, String nodeType,
-            String nodeId) {
+    private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
 
         Node node = Node.fromString(nodeType, nodeId);
         if (node == null) {
-            throw new ResourceNotFoundException(nodeId + " : "
-                    + RestMessages.NONODE.toString());
+            throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
         }
 
-        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
-                ISwitchManager.class, containerName, this);
+        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
 
         if (sm == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         if (!sm.getNodes().contains(node)) {
-            throw new ResourceNotFoundException(node.toString() + " : "
-                    + RestMessages.NONODE.toString());
+            throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString());
         }
         return node;
     }
 
-    private void handleNodeConnectorAvailability(String containerName,
-            Node node, String nodeConnectorType, String nodeConnectorId) {
+    private void handleNodeConnectorAvailability(String containerName, Node node, String nodeConnectorType,
+            String nodeConnectorId) {
 
-        NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType,
-                nodeConnectorId, node);
+        NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
         if (nc == null) {
-            throw new ResourceNotFoundException(nc + " : "
-                    + RestMessages.NORESOURCE.toString());
+            throw new ResourceNotFoundException(nc + " : " + RestMessages.NORESOURCE.toString());
         }
 
-        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
-                ISwitchManager.class, containerName, this);
+        ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
 
         if (sm == null) {
-            throw new ServiceUnavailableException("Switch Manager "
-                    + RestMessages.SERVICEUNAVAILABLE.toString());
+            throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
 
         if (!sm.getNodeConnectors(node).contains(nc)) {
-            throw new ResourceNotFoundException(nc.toString() + " : "
-                    + RestMessages.NORESOURCE.toString());
+            throw new ResourceNotFoundException(nc.toString() + " : " + RestMessages.NORESOURCE.toString());
         }
     }
 
@@ -771,15 +715,14 @@ public class SwitchNorthbound {
         if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
             return true;
         }
-        IContainerManager containerManager = (IContainerManager) ServiceHelper
-                .getGlobalInstance(IContainerManager.class, this);
+        IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
+                IContainerManager.class, this);
         if (containerManager == null) {
-            throw new InternalServerErrorException(
-                    RestMessages.INTERNALERROR.toString());
+            throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString());
         }
         if (containerManager.getContainerNames().contains(containerName)) {
             return true;
-       }
+        }
         return false;
     }
 
index ff26bfd21f30a6b67f683607924b366ef32a1011..461f452d188611cb02f3d9312c2b58f6ea3f4f59 100644 (file)
@@ -25,7 +25,6 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
-import javax.xml.bind.JAXBElement;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -37,6 +36,7 @@ import org.opendaylight.controller.northbound.commons.exception.UnauthorizedExce
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Edge;
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
@@ -62,7 +62,9 @@ public class TopologyNorthboundJAXRS {
 
     @Context
     public void setSecurityContext(SecurityContext context) {
-        if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
+        if (context != null && context.getUserPrincipal() != null) {
+            username = context.getUserPrincipal().getName();
+        }
     }
 
     protected String getUserName() {
@@ -179,17 +181,14 @@ public class TopologyNorthboundJAXRS {
     @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") })
     public Topology getTopology(@PathParam("containerName") String containerName) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
-        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
-                .getInstance(ITopologyManager.class, containerName, this);
+        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class,
+                containerName, this);
         if (topologyManager == null) {
-            throw new ResourceNotFoundException(
-                    RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString());
         }
 
         Map<Edge, Set<Property>> topo = topologyManager.getEdges();
@@ -209,11 +208,12 @@ public class TopologyNorthboundJAXRS {
      * Retrieve the user configured links
      *
      * @param containerName
-     *            The container for which we want to retrieve the user links (Eg. 'default')
+     *            The container for which we want to retrieve the user links
+     *            (Eg. 'default')
      *
      * @return A List of user configured links
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -242,27 +242,21 @@ public class TopologyNorthboundJAXRS {
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(TopologyUserLinks.class)
     @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") })
-    public TopologyUserLinks getUserLinks(
-            @PathParam("containerName") String containerName) {
+    public TopologyUserLinks getUserLinks(@PathParam("containerName") String containerName) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.READ, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
-        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
-                .getInstance(ITopologyManager.class, containerName, this);
+        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class,
+                containerName, this);
         if (topologyManager == null) {
-            throw new ResourceNotFoundException(
-                    RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString());
         }
 
-        ConcurrentMap<String, TopologyUserLinkConfig> userLinks = topologyManager
-                .getUserLinks();
+        ConcurrentMap<String, TopologyUserLinkConfig> userLinks = topologyManager.getUserLinks();
         if ((userLinks != null) && (userLinks.values() != null)) {
-            List<TopologyUserLinkConfig> res = new ArrayList<TopologyUserLinkConfig>(
-                    userLinks.values());
+            List<TopologyUserLinkConfig> res = new ArrayList<TopologyUserLinkConfig>(userLinks.values());
             return new TopologyUserLinks(res);
         }
 
@@ -280,7 +274,7 @@ public class TopologyNorthboundJAXRS {
      *            in JSON or XML format
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -306,32 +300,34 @@ public class TopologyNorthboundJAXRS {
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({
-            @ResponseCode(code = 201, condition = "User Link added successfully"),
-            @ResponseCode(code = 404, condition = "The Container Name was not found"),
-            @ResponseCode(code = 409, condition = "Failed to add User Link due to Conflicting Name"),
-            @ResponseCode(code = 500, condition = "Failed to add User Link. Failure Reason included in HTTP Error response"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response addUserLink(
-            @PathParam(value = "containerName") String containerName,
+        @ResponseCode(code = 201, condition = "User Link added successfully"),
+        @ResponseCode(code = 404, condition = "The Container Name was not found"),
+        @ResponseCode(code = 409, condition = "Failed to add User Link due to Conflicting Name"),
+        @ResponseCode(code = 500, condition = "Failed to add User Link. Failure Reason included in HTTP Error response"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response addUserLink(@PathParam(value = "containerName") String containerName,
             @PathParam(value = "name") String name,
             @TypeHint(TopologyUserLinkConfig.class) TopologyUserLinkConfig userLinkConfig) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
-        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
-                .getInstance(ITopologyManager.class, containerName, this);
+        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class,
+                containerName, this);
         if (topologyManager == null) {
-            throw new ResourceNotFoundException(
-                    RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString());
         }
 
         Status status = topologyManager.addUserLink(userLinkConfig);
         if (status.isSuccess()) {
-            NorthboundUtils.auditlog("User Link", username, "added", userLinkConfig.getName(), containerName);
+            NorthboundUtils
+            .auditlog(
+                    "User Link",username,"added", userLinkConfig.getName() + " from " + NorthboundUtils.getPortName(
+                            NodeConnector.fromString(userLinkConfig.getSrcNodeConnector()),
+                            containerName, this) + " to "
+                            + NorthboundUtils.getPortName(NodeConnector.fromString
+                                    (userLinkConfig.getDstNodeConnector()),containerName, this), containerName);
             return Response.status(Response.Status.CREATED).build();
         }
         throw new InternalServerErrorException(status.getDescription());
@@ -346,7 +342,7 @@ public class TopologyNorthboundJAXRS {
      *            Name of the Link Configuration (Eg. 'config1')
      * @return Response as dictated by the HTTP Response Status code
      *
-     * <pre>
+     *         <pre>
      *
      * Example:
      *
@@ -359,25 +355,19 @@ public class TopologyNorthboundJAXRS {
     @DELETE
     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-    @StatusCodes({
-            @ResponseCode(code = 204, condition = "User link removed successfully"),
-            @ResponseCode(code = 404, condition = "The Container Name or Link Configuration Name was not found"),
-            @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
-    public Response deleteUserLink(
-            @PathParam("containerName") String containerName,
-            @PathParam("name") String name) {
+    @StatusCodes({ @ResponseCode(code = 204, condition = "User link removed successfully"),
+        @ResponseCode(code = 404, condition = "The Container Name or Link Configuration Name was not found"),
+        @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
+    public Response deleteUserLink(@PathParam("containerName") String containerName, @PathParam("name") String name) {
 
-        if (!NorthboundUtils.isAuthorized(
-                getUserName(), containerName, Privilege.WRITE, this)) {
-            throw new UnauthorizedException(
-                    "User is not authorized to perform this operation on container "
-                            + containerName);
+        if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
+            throw new UnauthorizedException("User is not authorized to perform this operation on container "
+                    + containerName);
         }
-        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
-                .getInstance(ITopologyManager.class, containerName, this);
+        ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class,
+                containerName, this);
         if (topologyManager == null) {
-            throw new ResourceNotFoundException(
-                    RestMessages.NOCONTAINER.toString());
+            throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString());
         }
 
         Status ret = topologyManager.deleteUserLink(name);
index 2b8f6553d61cb6202f0576b92b4b5890bc30e7f5..daf1aa8b7168a8b3a4670f21d0468036e42a380f 100644 (file)
@@ -557,6 +557,7 @@ public class FlowConverter {
                         byte tos = (byte) (dscp >> 2);
                         salMatch.setField(MatchType.NW_TOS, tos);
                     }
+                    //TODO: NW protocol 0 is a valid protocol
                     if (ofMatch.getNetworkProtocol() != 0) {
                         salMatch.setField(MatchType.NW_PROTO,
                                 ofMatch.getNetworkProtocol());
index 66e6e65706fc2b23a1498b589a4e94fafbe3e7bf..d3d3142cdfbcf7f06dc81d5cd49d95f0038ee971 100644 (file)
@@ -13,24 +13,25 @@ import java.util.ArrayList;
 import java.util.List;
 
 /**
- * It represents the most common IP protocols numbers
- * It provides the binding between IP protocol names and numbers
- * and provides APIs to read and parse them in either of the two forms
- *
+ * Enum represents the most common IP protocols numbers It provides the binding
+ * between IP protocol names and numbers and provides APIs to read and parse
+ * them in either of the two forms
  *
+ * NOTE: Openflow 1.0 supports the IP Proto match only for ICMP, TCP and UDP
  *
+ * references:
+ * http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  */
-// Openflow 1.0 supports the IP Proto match only for ICMP, TCP and UDP
 public enum IPProtocols {
-    ANY("any", 0),
-    /*  HOPOPT("HOPOPT",0),
-     */ICMP("ICMP", 1),
-    /*  IGMP("IGMP",2),
+     ANY("any", -1),
+     HOPOPT("HOPOPT",0),
+     ICMP("ICMP", 1),
+     IGMP("IGMP",2),
      GGP("GGP",3),
      IPV4("IPv4",4),
      ST("ST",5),
-     */TCP("TCP", 6),
-    /*  CBT("CBT",7),
+     TCP("TCP", 6),
+     CBT("CBT",7),
      EGP("EGP",8),
      IGP("IGP",9),
      BBNRCCMON("BBN-RCC-MON",10),
@@ -40,8 +41,8 @@ public enum IPProtocols {
      EMCON("EMCON",14),
      XNET("XNET",15),
      CHAOS("CHAOS",16),
-     */UDP("UDP", 17),
-    /*  MUX("MUX",18),
+     UDP("UDP", 17),
+     MUX("MUX",18),
      DCNMEAS("DCN-MEAS",19),
      HMP("HMP",20),
      PRM("PRM",21),
@@ -81,8 +82,8 @@ public enum IPProtocols {
      MOBILE("MOBILE",55),
      TLSP("TLSP",56),
      SKIP("SKIP",57),
-     */IPV6ICMP("IPv6-ICMP", 58);
-    /*  IPV6NoNxt("IPv6-NoNxt",59),
+     IPV6ICMP("IPv6-ICMP", 58),
+     IPV6NoNxt("IPv6-NoNxt",59),
      IPV6Opts("IPv6-Opts",60),
      ANYHOST("ANY-HOST",61),
      CFTP("CFTP",62),
@@ -166,10 +167,15 @@ public enum IPProtocols {
      HIP("HIP",139),
      SHIM6("Shim6",140),
      WESP("WESP",141),
-     ROHC("ROHC",142);
-     */
-    private static final String regexDecimalString = "^[0-9]{3}$";
-    private static final String regexHexString = "^(0(x|X))[0-9a-fA-F]{2}$";
+     ROHC("ROHC",142),
+     /*143-252 Unassigned by IANA*/
+
+     //Experimebtal protocol numbers (http://tools.ietf.org/html/rfc3692)
+     EXP1("Experimental1", 253),
+     EXP2("Experimental2", 254),
+
+     RESERVED("RESERVED",255);
+
     private String protocolName;
     private int protocolNumber;
 
@@ -190,6 +196,7 @@ public enum IPProtocols {
         return ((Integer) protocolNumber).byteValue();
     }
 
+    @Override
     public String toString() {
         return protocolName;
     }
@@ -199,11 +206,11 @@ public enum IPProtocols {
     }
 
     public static String getProtocolName(short number) {
-        return getProtocolNameInternal((int) number & 0xffff);
+        return getProtocolNameInternal(number & 0xffff);
     }
 
     public static String getProtocolName(byte number) {
-        return getProtocolNameInternal((int) number & 0xff);
+        return getProtocolNameInternal(number & 0xff);
     }
 
     private static String getProtocolNameInternal(int number) {
@@ -212,52 +219,35 @@ public enum IPProtocols {
                 return proto.toString();
             }
         }
+        //TODO: this is for backwards compatibility
         return "0x" + Integer.toHexString(number);
     }
 
     public static short getProtocolNumberShort(String name) {
-        if (name.matches(regexHexString)) {
-            return Short.valueOf(Short.decode(name));
-        }
-        if (name.matches(regexDecimalString)) {
-            return Short.valueOf(name);
+        IPProtocols p = fromString(name);
+        if (p != null) {
+            return p.shortValue();
         }
-        for (IPProtocols proto : IPProtocols.values()) {
-            if (proto.protocolName.equalsIgnoreCase(name)) {
-                return proto.shortValue();
-            }
-        }
-        return 0;
+        //This method should be called after validation only
+        throw new IllegalArgumentException("Illegal IP protocol value: " + name);
     }
 
     public static int getProtocolNumberInt(String name) {
-        if (name.matches(regexHexString)) {
-            return Integer.valueOf(Integer.decode(name));
-        }
-        if (name.matches(regexDecimalString)) {
-            return Integer.valueOf(name);
-        }
-        for (IPProtocols proto : IPProtocols.values()) {
-            if (proto.protocolName.equalsIgnoreCase(name)) {
-                return proto.intValue();
-            }
+        IPProtocols p = fromString(name);
+        if (p != null) {
+            return p.intValue();
         }
-        return 0;
+        //This method should be called after validation only
+        throw new IllegalArgumentException("Illegal IP protocol value: " + name);
     }
 
     public static byte getProtocolNumberByte(String name) {
-        if (name.matches(regexHexString)) {
-            return Integer.valueOf(Integer.decode(name)).byteValue();
+        IPProtocols p = fromString(name);
+        if (p != null) {
+            return p.byteValue();
         }
-        if (name.matches(regexDecimalString)) {
-            return Integer.valueOf(name).byteValue();
-        }
-        for (IPProtocols proto : IPProtocols.values()) {
-            if (proto.protocolName.equalsIgnoreCase(name)) {
-                return proto.byteValue();
-            }
-        }
-        return 0;
+        //This method should be called after validation only
+        throw new IllegalArgumentException("Illegal IP protocol value: " + name);
     }
 
     public static List<String> getProtocolNameList() {
@@ -267,4 +257,47 @@ public enum IPProtocols {
         }
         return protoList;
     }
+
+    /**
+     * Method to parse an IPProtocol from a numeric string
+     * (see: {@link Java.Lang.Integer.decode(java.lang.String)} for parsable strings),
+     * or this enum's name string.
+     *
+     * @param s
+     *            The IP protocol string to be parsed
+     * @return The IP protocol Enum, or null if invalid protocol string is passed
+     */
+    public static IPProtocols fromString(String s) {
+        // null/empty/any/* evaluates to ANY
+        if (s == null || s.isEmpty() || s.equalsIgnoreCase("any") || s.equals("*")) {
+            return IPProtocols.ANY;
+        }
+
+        // Try parsing numeric and find the related ENUM
+        try {
+            int protoNum = Integer.decode(s);
+            for (IPProtocols protoEnum : IPProtocols.values()) {
+                if (protoEnum.protocolNumber == protoNum) {
+                    return protoEnum;
+                }
+            }
+            // At this point it's an invalid number (i.e. out of range or not a valid proto num)
+            return null;
+        } catch (NumberFormatException nfe) {
+            // numeric failed try by NAME
+            try {
+                return valueOf(s);
+            } catch(IllegalArgumentException e) {
+                // Neither numeric nor enum NAME, attempt human readable name
+                for (IPProtocols protoEnum : IPProtocols.values()) {
+                    if (protoEnum.toString().equalsIgnoreCase(s)) {
+                        return protoEnum;
+                    }
+                }
+                //couldn't parse, signifies an invalid proto field!
+                return null;
+            }
+
+        }
+    }
 }
diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java
new file mode 100644 (file)
index 0000000..fc6d78c
--- /dev/null
@@ -0,0 +1,107 @@
+/**
+ *
+ */
+package org.opendaylight.controller.sal.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * @author ykhodork
+ *
+ */
+public class IPProtocolsTest {
+
+    static short shortVal = 1;
+    static int   intVal = 1;
+    static byte  byteVal = 1;
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(int)}.
+     */
+    @Test
+    public void testGetProtocolNameInt() {
+        assertEquals("ICMP", IPProtocols.getProtocolName(1));
+        assertEquals("0x4d2", IPProtocols.getProtocolName(1234));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(short)}.
+     */
+    @Test
+    public void testGetProtocolNameShort() {
+        assertEquals("ICMP", IPProtocols.getProtocolName(shortVal));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(byte)}.
+     */
+    @Test
+    public void testGetProtocolNameByte() {
+        assertEquals("ICMP", IPProtocols.getProtocolName(byteVal));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberShort(java.lang.String)}.
+     */
+    @Test
+    public void testGetProtocolNumberShort() {
+        assertEquals(shortVal, IPProtocols.getProtocolNumberShort("ICMP"));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberInt(java.lang.String)}.
+     */
+    @Test
+    public void testGetProtocolNumberInt() {
+        assertEquals(intVal, IPProtocols.getProtocolNumberInt("ICMP"));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberByte(java.lang.String)}.
+     */
+    @Test
+    public void testGetProtocolNumberByte() {
+        assertEquals(byteVal, IPProtocols.getProtocolNumberByte("ICMP"));
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#fromString(java.lang.String)}.
+     */
+    @Test
+    public void testFromString() {
+        assertTrue(null == IPProtocols.fromString("Not a protocol"));
+        assertTrue(null == IPProtocols.fromString("0xFFF"));
+        assertTrue(null == IPProtocols.fromString("-2"));
+
+        assertTrue(IPProtocols.ANY == IPProtocols.fromString("any"));
+        assertTrue(IPProtocols.ANY == IPProtocols.fromString("ANY"));
+        assertTrue(IPProtocols.ANY == IPProtocols.fromString("*"));
+        assertTrue(IPProtocols.ANY == IPProtocols.fromString(null));
+
+        assertTrue(IPProtocols.TCP == IPProtocols.fromString("TCP"));
+        assertTrue(IPProtocols.TCP == IPProtocols.fromString("tcp"));
+        assertTrue(IPProtocols.UDP == IPProtocols.fromString("0x11"));
+        assertTrue(IPProtocols.UDP == IPProtocols.fromString("0X11"));
+
+    }
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
index 6ca60e857d8a86963be038ca1c4714050d7bff39..34688cbb634eeede8c0ebfae25a121e673712bf4 100644 (file)
@@ -91,11 +91,9 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getNodesLearnt(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
+    public DevicesJsonBean getNodesLearnt(HttpServletRequest request, @RequestParam(required = false) String container) {
         Gson gson = new Gson();
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
@@ -141,44 +139,35 @@ public class Devices implements IDaylightWeb {
                     for (NodeConnector nodeConnector : nodeConnectorSet) {
                         String nodeConnectorNumberToStr = nodeConnector.getID().toString();
                         Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName));
-                        Config portStatus = ((Config) switchManager
-                                .getNodeConnectorProp(nodeConnector,
-                                        Config.ConfigPropName));
-                        State portState = ((State) switchManager
-                                .getNodeConnectorProp(nodeConnector,
-                                        State.StatePropName));
-                        String nodeConnectorName = (ncName != null) ? ncName
-                                .getValue() : "";
+                        Config portStatus = ((Config) switchManager.getNodeConnectorProp(nodeConnector,
+                                Config.ConfigPropName));
+                        State portState = ((State) switchManager.getNodeConnectorProp(nodeConnector,
+                                State.StatePropName));
+                        String nodeConnectorName = (ncName != null) ? ncName.getValue() : "";
                         nodeConnectorName += " (" + nodeConnector.getID() + ")";
 
                         if (portStatus != null) {
                             if (portStatus.getValue() == Config.ADMIN_UP) {
                                 if (portState.getValue() == State.EDGE_UP) {
-                                    nodeConnectorName = "<span class='admin-up'>"
-                                            + nodeConnectorName + "</span>";
+                                    nodeConnectorName = "<span class='admin-up'>" + nodeConnectorName + "</span>";
                                 } else if (portState.getValue() == State.EDGE_DOWN) {
-                                    nodeConnectorName = "<span class='edge-down'>"
-                                            + nodeConnectorName + "</span>";
+                                    nodeConnectorName = "<span class='edge-down'>" + nodeConnectorName + "</span>";
                                 }
                             } else if (portStatus.getValue() == Config.ADMIN_DOWN) {
-                                nodeConnectorName = "<span class='admin-down'>"
-                                        + nodeConnectorName + "</span>";
+                                nodeConnectorName = "<span class='admin-down'>" + nodeConnectorName + "</span>";
                             }
                         }
 
                         Class<?> idClass = nodeConnector.getID().getClass();
                         if (idClass.equals(Short.class)) {
-                            portList.put(
-                                    Short.parseShort(nodeConnectorNumberToStr),
-                                    nodeConnectorName);
+                            portList.put(Short.parseShort(nodeConnectorNumberToStr), nodeConnectorName);
                         } else {
                             intfList.add(nodeConnectorName);
                         }
                     }
 
                     if (portList.size() > 0) {
-                        Map<Short, String> sortedPortList = new TreeMap<Short, String>(
-                                portList);
+                        Map<Short, String> sortedPortList = new TreeMap<Short, String>(portList);
 
                         for (Entry<Short, String> e : sortedPortList.entrySet()) {
                             sb1.append(e.getValue());
@@ -219,27 +208,22 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/nodesLearnt/update", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean updateLearntNode(
-            @RequestParam("nodeName") String nodeName,
-            @RequestParam("nodeId") String nodeId,
-            @RequestParam("tier") String tier,
-            @RequestParam("operationMode") String operationMode,
-            HttpServletRequest request,
+    public StatusJsonBean updateLearntNode(@RequestParam("nodeName") String nodeName,
+            @RequestParam("nodeId") String nodeId, @RequestParam("tier") String tier,
+            @RequestParam("operationMode") String operationMode, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             Map<String, Property> nodeProperties = new HashMap<String, Property>();
             Property desc = new Description(nodeName);
             nodeProperties.put(desc.getName(), desc);
@@ -257,37 +241,33 @@ public class Devices implements IDaylightWeb {
             } else {
                 resultBean.setStatus(true);
                 resultBean.setMessage("Updated node information successfully");
-                DaylightWebUtil.auditlog("Node", userName, "updated", nodeId + " to "+ nodeName, containerName);
+                DaylightWebUtil.auditlog("Property", userName, "updated",
+                        "of Node " + DaylightWebUtil.getNodeDesc(Node.fromString(nodeId), switchManager));
             }
         } catch (Exception e) {
             resultBean.setStatus(false);
-            resultBean.setMessage("Error updating node information. "
-                    + e.getMessage());
+            resultBean.setMessage("Error updating node information. " + e.getMessage());
         }
         return resultBean;
     }
 
     @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getStaticRoutes(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
+    public DevicesJsonBean getStaticRoutes(HttpServletRequest request, @RequestParam(required = false) String container) {
         Gson gson = new Gson();
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
 
-        IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
-                .getInstance(IForwardingStaticRouting.class, containerName,
-                        this);
+        IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
+                IForwardingStaticRouting.class, containerName, this);
         if (staticRouting == null) {
             return null;
         }
         List<Map<String, String>> staticRoutes = new ArrayList<Map<String, String>>();
-        ConcurrentMap<String, StaticRouteConfig> routeConfigs = staticRouting
-                .getStaticRouteConfigs();
+        ConcurrentMap<String, StaticRouteConfig> routeConfigs = staticRouting.getStaticRouteConfigs();
         if (routeConfigs == null) {
             return null;
         }
@@ -311,27 +291,21 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/staticRoute/add", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean addStaticRoute(
-            @RequestParam("routeName") String routeName,
-            @RequestParam("staticRoute") String staticRoute,
-            @RequestParam("nextHop") String nextHop,
-            HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public StatusJsonBean addStaticRoute(@RequestParam("routeName") String routeName,
+            @RequestParam("staticRoute") String staticRoute, @RequestParam("nextHop") String nextHop,
+            HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean result = new StatusJsonBean();
         try {
-            IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
-                    .getInstance(IForwardingStaticRouting.class, containerName,
-                            this);
+            IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
+                    IForwardingStaticRouting.class, containerName, this);
             StaticRouteConfig config = new StaticRouteConfig();
             config.setName(routeName);
             config.setStaticRoute(staticRoute);
@@ -354,12 +328,9 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/staticRoute/delete", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean deleteStaticRoute(
-            @RequestParam("routesToDelete") String routesToDelete,
-            HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public StatusJsonBean deleteStaticRoute(@RequestParam("routesToDelete") String routesToDelete,
+            HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -369,14 +340,12 @@ public class Devices implements IDaylightWeb {
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
-                    .getInstance(IForwardingStaticRouting.class, containerName,
-                            this);
+            IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
+                    IForwardingStaticRouting.class, containerName, this);
             String[] routes = routesToDelete.split(",");
             Status result;
             resultBean.setStatus(true);
-            resultBean
-                    .setMessage("Successfully deleted selected static routes");
+            resultBean.setMessage("Successfully deleted selected static routes");
             for (String route : routes) {
                 result = staticRouting.removeStaticRoute(route);
                 if (!result.isSuccess()) {
@@ -388,9 +357,7 @@ public class Devices implements IDaylightWeb {
             }
         } catch (Exception e) {
             resultBean.setStatus(false);
-            resultBean
-                    .setMessage("Error occurred while deleting static routes. "
-                            + e.getMessage());
+            resultBean.setMessage("Error occurred while deleting static routes. " + e.getMessage());
         }
         return resultBean;
     }
@@ -417,7 +384,7 @@ public class Devices implements IDaylightWeb {
                     subnet.put("subnet", conf.getSubnet());
                     List<SubnetGatewayPortBean> portsList = new ArrayList<SubnetGatewayPortBean>();
                     Iterator<NodeConnector> itor = conf.getNodeConnectors().iterator();
-                    while(itor.hasNext()) {
+                    while (itor.hasNext()) {
                         SubnetGatewayPortBean bean = new SubnetGatewayPortBean();
                         NodeConnector nodeConnector = itor.next();
                         String nodeName = getNodeDesc(nodeConnector.getNode().toString(), containerName);
@@ -443,13 +410,10 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/subnetGateway/add", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean addSubnetGateways(
-            @RequestParam("gatewayName") String gatewayName,
-            @RequestParam("gatewayIPAddress") String gatewayIPAddress,
-            HttpServletRequest request,
+    public StatusJsonBean addSubnetGateways(@RequestParam("gatewayName") String gatewayName,
+            @RequestParam("gatewayIPAddress") String gatewayIPAddress, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -459,10 +423,9 @@ public class Devices implements IDaylightWeb {
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
-            SubnetConfig cfgObject = new SubnetConfig(gatewayName,
-                    gatewayIPAddress, new ArrayList<String>());
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
+            SubnetConfig cfgObject = new SubnetConfig(gatewayName, gatewayIPAddress, new ArrayList<String>());
             Status result = switchManager.addSubnet(cfgObject);
             if (result.isSuccess()) {
                 resultBean.setStatus(true);
@@ -481,12 +444,9 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/subnetGateway/delete", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean deleteSubnetGateways(
-            @RequestParam("gatewaysToDelete") String gatewaysToDelete,
-            HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public StatusJsonBean deleteSubnetGateways(@RequestParam("gatewaysToDelete") String gatewaysToDelete,
+            HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -496,8 +456,8 @@ public class Devices implements IDaylightWeb {
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             String[] subnets = gatewaysToDelete.split(",");
             resultBean.setStatus(true);
             resultBean.setMessage("Added gateway address successfully");
@@ -519,13 +479,10 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/subnetGateway/ports/add", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean addSubnetGatewayPort(
-            @RequestParam("portsName") String portsName,
-            @RequestParam("ports") String ports,
-            @RequestParam("nodeId") String nodeId, HttpServletRequest request,
+    public StatusJsonBean addSubnetGatewayPort(@RequestParam("portsName") String portsName,
+            @RequestParam("ports") String ports, @RequestParam("nodeId") String nodeId, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -535,8 +492,8 @@ public class Devices implements IDaylightWeb {
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             List<String> toAdd = new ArrayList<String>();
             for (String port : ports.split(",")) {
                 toAdd.add(port);
@@ -545,9 +502,12 @@ public class Devices implements IDaylightWeb {
 
             if (result.isSuccess()) {
                 resultBean.setStatus(true);
-                resultBean
-                        .setMessage("Added ports to subnet gateway address successfully");
-                DaylightWebUtil.auditlog("Ports to Subnet Gateway", userName, "added", ports, containerName);
+                resultBean.setMessage("Added ports to subnet gateway address successfully");
+                for (String port : toAdd) {
+                    DaylightWebUtil.auditlog("Port", userName, "added",
+                            DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager)
+                            + " to Subnet Gateway " + portsName, containerName);
+                }
             } else {
                 resultBean.setStatus(false);
                 resultBean.setMessage(result.getDescription());
@@ -561,13 +521,10 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/subnetGateway/ports/delete", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean deleteSubnetGatewayPort(
-            @RequestParam("gatewayName") String gatewayName,
-            @RequestParam("nodePort") String nodePort,
-            HttpServletRequest request,
+    public StatusJsonBean deleteSubnetGatewayPort(@RequestParam("gatewayName") String gatewayName,
+            @RequestParam("nodePort") String nodePort, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -577,8 +534,8 @@ public class Devices implements IDaylightWeb {
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             List<String> toRemove = new ArrayList<String>();
             for (String port : nodePort.split(",")) {
                 toRemove.add(port);
@@ -588,7 +545,11 @@ public class Devices implements IDaylightWeb {
             if (result.isSuccess()) {
                 resultBean.setStatus(true);
                 resultBean.setMessage("Deleted port from subnet gateway address successfully");
-                DaylightWebUtil.auditlog("Ports from Subnet Gateway", userName, "removed", nodePort, containerName);
+                for (String port : toRemove) {
+                    DaylightWebUtil.auditlog("Port", userName, "removed",
+                            DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager)
+                            + " from Subnet Gateway " + gatewayName, containerName);
+                }
             } else {
                 resultBean.setStatus(false);
                 resultBean.setMessage(result.getDescription());
@@ -602,22 +563,19 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getSpanPorts(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
+    public DevicesJsonBean getSpanPorts(HttpServletRequest request, @RequestParam(required = false) String container) {
         Gson gson = new Gson();
         List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
-        Privilege privilege = DaylightWebUtil.getContainerPrivilege(
-                userName, containerName, this);
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
 
         if (privilege != Privilege.NONE) {
             List<String> spanConfigs_json = new ArrayList<String>();
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             if (switchManager != null) {
                 for (SpanConfig conf : switchManager.getSpanConfigList()) {
                     spanConfigs_json.add(gson.toJson(conf));
@@ -628,14 +586,12 @@ public class Devices implements IDaylightWeb {
             for (String config_json : spanConfigs_json) {
                 try {
                     @SuppressWarnings("unchecked")
-                    Map<String, String> config_data = mapper.readValue(config_json,
-                            HashMap.class);
+                    Map<String, String> config_data = mapper.readValue(config_json, HashMap.class);
                     Map<String, String> config = new HashMap<String, String>();
                     for (String name : config_data.keySet()) {
                         config.put(name, config_data.get(name));
                         // Add switch portName value (non-configuration field)
-                        config.put("nodeName",
-                                getNodeDesc(config_data.get("nodeId"), containerName));
+                        config.put("nodeName", getNodeDesc(config_data.get("nodeId"), containerName));
                         NodeConnector spanPortNodeConnector = NodeConnector.fromString(config_data.get("spanPort"));
                         Name ncName = ((Name) switchManager.getNodeConnectorProp(spanPortNodeConnector,
                                 Name.NamePropName));
@@ -668,8 +624,8 @@ public class Devices implements IDaylightWeb {
             return null;
         }
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             return null;
         }
@@ -681,9 +637,10 @@ public class Devices implements IDaylightWeb {
             Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
             if (nodeConnectorSet != null) {
                 for (NodeConnector nodeConnector : nodeConnectorSet) {
-                    String nodeConnectorName = ((Name) switchManager
-                            .getNodeConnectorProp(nodeConnector, Name.NamePropName)).getValue();
-                    port.add(new PortJsonBean(nodeConnector.getID().toString(), nodeConnectorName, nodeConnector.toString()));
+                    String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
+                            Name.NamePropName)).getValue();
+                    port.add(new PortJsonBean(nodeConnector.getID().toString(), nodeConnectorName, nodeConnector
+                            .toString()));
                 }
             }
             nodeJsonBean.setNodeId(node.getNode().toString());
@@ -697,12 +654,9 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/spanPorts/add", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean addSpanPort(
-            @RequestParam("jsonData") String jsonData,
-            HttpServletRequest request,
+    public StatusJsonBean addSpanPort(@RequestParam("jsonData") String jsonData, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -713,34 +667,32 @@ public class Devices implements IDaylightWeb {
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
             Gson gson = new Gson();
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
             SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
             Status result = switchManager.addSpanConfig(cfgObject);
             if (result.isSuccess()) {
                 resultBean.setStatus(true);
                 resultBean.setMessage("SPAN Port added successfully");
-                DaylightWebUtil.auditlog("SPAN Port", userName, "added", cfgObject.getNodeId(), containerName);
+                DaylightWebUtil.auditlog("SPAN Port", userName, "added",
+                        DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager),
+                        containerName);
             } else {
                 resultBean.setStatus(false);
                 resultBean.setMessage(result.getDescription());
             }
         } catch (Exception e) {
             resultBean.setStatus(false);
-            resultBean.setMessage("Error occurred while adding span port. "
-                    + e.getMessage());
+            resultBean.setMessage("Error occurred while adding span port. " + e.getMessage());
         }
         return resultBean;
     }
 
     @RequestMapping(value = "/spanPorts/delete", method = RequestMethod.GET)
     @ResponseBody
-    public StatusJsonBean deleteSpanPorts(
-            @RequestParam("spanPortsToDelete") String spanPortsToDelete,
-            HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public StatusJsonBean deleteSpanPorts(@RequestParam("spanPortsToDelete") String spanPortsToDelete,
+            HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
@@ -751,43 +703,44 @@ public class Devices implements IDaylightWeb {
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
             Gson gson = new Gson();
-            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                    .getInstance(ISwitchManager.class, containerName, this);
-            Type collectionType = new TypeToken<List<SpanPortJsonBean>>() {}.getType();
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
+                    containerName, this);
+            Type collectionType = new TypeToken<List<SpanPortJsonBean>>() {
+            }.getType();
             List<SpanPortJsonBean> jsonBeanList = gson.fromJson(spanPortsToDelete, collectionType);
             for (SpanPortJsonBean jsonBean : jsonBeanList) {
-                SpanConfig cfgObject = gson
-                        .fromJson(gson.toJson(jsonBean), SpanConfig.class);
+                SpanConfig cfgObject = gson.fromJson(gson.toJson(jsonBean), SpanConfig.class);
                 Status result = switchManager.removeSpanConfig(cfgObject);
                 if (!result.isSuccess()) {
                     resultBean.setStatus(false);
                     resultBean.setMessage(result.getDescription());
                     break;
                 }
-                DaylightWebUtil.auditlog("SPAN Port", userName, "removed", cfgObject.getNodeId(), containerName);
+                DaylightWebUtil.auditlog("SPAN Port", userName, "removed",
+                        DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager),
+                        containerName);
             }
             resultBean.setStatus(true);
             resultBean.setMessage("SPAN Port(s) deleted successfully");
         } catch (Exception e) {
             resultBean.setStatus(false);
-            resultBean.setMessage("Error occurred while deleting span port. "
-                    + e.getMessage());
+            resultBean.setMessage("Error occurred while deleting span port. " + e.getMessage());
         }
         return resultBean;
     }
 
     private String getNodeDesc(String nodeId, String containerName) {
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         String description = "";
         if (switchManager != null) {
-            Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId), Description.propertyName);
-            if(desc != null) {
+            Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId),
+                    Description.propertyName);
+            if (desc != null) {
                 description = desc.getValue();
             }
         }
-        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId
-                : description;
+        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId : description;
     }
 
     private StatusJsonBean unauthorizedMessage() {
@@ -798,8 +751,7 @@ public class Devices implements IDaylightWeb {
     }
 
     @RequestMapping(value = "login")
-    public String login(final HttpServletRequest request,
-            final HttpServletResponse response) {
+    public String login(final HttpServletRequest request, final HttpServletResponse response) {
         // response.setHeader("X-Page-Location", "/login");
         /*
          * IUserManager userManager = (IUserManager) ServiceHelper
@@ -815,4 +767,4 @@ public class Devices implements IDaylightWeb {
         return "forward:" + "/";
     }
 
-}
+}
\ No newline at end of file
index 2488d06d0cae7745a4efc58c8d8a42ff1f565271..e6f75c2c3847d57b7c2b71f46ec5972550706f08 100644 (file)
@@ -1326,6 +1326,7 @@ one.f.switchmanager.spanPortConfig = {
             var $label = one.lib.form.label("Node");
             var $select = one.lib.form.select.create(nodes);
             one.lib.form.select.prepend($select, { '' : 'Please Select a Node' });
+            $select.val($select.find("option:first").val());
             $select.attr('id', one.f.switchmanager.spanPortConfig.id.modal.form.nodes);
             
             // bind onchange
index 4cd71a37640ba2f303c04570eb9549c845a82816..a014528ded3ccfea19f47ea21ecae64ec83d513c 100644 (file)
@@ -81,29 +81,26 @@ public class Flows implements IDaylightWeb {
 
     @RequestMapping(value = "/main")
     @ResponseBody
-    public Map<String, Object> getFlows(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public Map<String, Object> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
-        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName,
-                containerName, this);
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
         if (privilege == Privilege.NONE) {
             return null;
         }
 
         // fetch frm
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
             return null;
         }
 
         // fetch sm
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             return null;
         }
@@ -129,20 +126,17 @@ public class Flows implements IDaylightWeb {
 
     @RequestMapping(value = "/node-ports")
     @ResponseBody
-    public Map<String, Object> getNodePorts(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
             return null;
         }
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             return null;
         }
@@ -156,12 +150,10 @@ public class Flows implements IDaylightWeb {
 
             if (nodeConnectorSet != null) {
                 for (NodeConnector nodeConnector : nodeConnectorSet) {
-                    String nodeConnectorName = ((Name) switchManager
-                            .getNodeConnectorProp(nodeConnector,
-                                    Name.NamePropName)).getValue();
-                    port.put((Short) nodeConnector.getID(), nodeConnectorName
-                            + "(" + nodeConnector.getNodeConnectorIDString()
-                            + ")");
+                    String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
+                            Name.NamePropName)).getValue();
+                    port.put((Short) nodeConnector.getID(),
+                            nodeConnectorName + "(" + nodeConnector.getNodeConnectorIDString() + ")");
                 }
             }
 
@@ -181,25 +173,22 @@ public class Flows implements IDaylightWeb {
 
     @RequestMapping(value = "/node-flows")
     @ResponseBody
-    public Map<String, Object> getNodeFlows(HttpServletRequest request,
-            @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+    public Map<String, Object> getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Derive the privilege this user has on the current container
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
             return null;
         }
 
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
+                this);
         if (switchManager == null) {
             return null;
         }
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
             return null;
         }
@@ -212,12 +201,9 @@ public class Flows implements IDaylightWeb {
             List<FlowConfig> flows = frm.getStaticFlows(node);
 
             String nodeDesc = node.toString();
-            SwitchConfig config = switchManager
-                    .getSwitchConfig(node.toString());
-            if ((config != null)
-                    && (config.getProperty(Description.propertyName) != null)) {
-                nodeDesc = ((Description) config
-                        .getProperty(Description.propertyName)).getValue();
+            SwitchConfig config = switchManager.getSwitchConfig(node.toString());
+            if ((config != null) && (config.getProperty(Description.propertyName) != null)) {
+                nodeDesc = ((Description) config.getProperty(Description.propertyName)).getValue();
             }
 
             nodes.put(nodeDesc, flows.size());
@@ -228,23 +214,19 @@ public class Flows implements IDaylightWeb {
 
     @RequestMapping(value = "/flow", method = RequestMethod.POST)
     @ResponseBody
-    public String actionFlow(@RequestParam(required = true) String action,
-            @RequestParam(required = false) String body,
-            @RequestParam(required = true) String nodeId,
-            HttpServletRequest request,
+    public String actionFlow(@RequestParam(required = true) String action, @RequestParam(required = false) String body,
+            @RequestParam(required = true) String nodeId, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return "Operation not authorized";
         }
 
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
             return null;
         }
@@ -253,36 +235,34 @@ public class Flows implements IDaylightWeb {
 
         Node node = Node.fromString(nodeId);
         flow.setNode(node);
+
         Status result = new Status(StatusCode.BADREQUEST, "Invalid request");
         if (action.equals("add")) {
             result = frm.addStaticFlow(flow);
-            DaylightWebUtil.auditlog("Flow", userName, "added", flow.getName(),
-                    containerName);
+            if (result.isSuccess()) {
+                DaylightWebUtil.auditlog("Flow Entry", userName, "added", flow.getName() + " on Node "
+                        + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
+            }
         }
 
-        return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result
-                .getDescription();
+        return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription();
     }
 
     @RequestMapping(value = "/flow/{nodeId}/{name:.*}", method = RequestMethod.POST)
     @ResponseBody
-    public String removeFlow(@PathVariable("nodeId") String nodeId,
-            @PathVariable("name") String name,
-            @RequestParam(required = true) String action,
-            HttpServletRequest request,
+    public String removeFlow(@PathVariable("nodeId") String nodeId, @PathVariable("name") String name,
+            @RequestParam(required = true) String action, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return "Operation not authorized";
         }
 
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
             return null;
         }
@@ -295,42 +275,36 @@ public class Flows implements IDaylightWeb {
         if (action.equals("remove")) {
             result = frm.removeStaticFlow(name, node);
             if (result.isSuccess()) {
-                DaylightWebUtil.auditlog("Flow", userName, "removed", name,
-                        containerName);
+                DaylightWebUtil.auditlog("Flow Entry", userName, "removed",
+                        name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
             }
         } else if (action.equals("toggle")) {
             result = frm.toggleStaticFlowStatus(name, node);
             if (result.isSuccess()) {
-                DaylightWebUtil.auditlog("Flow", userName, "toggled", name,
-                        containerName);
+                DaylightWebUtil.auditlog("Flow Entry", userName, "toggled",
+                        name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
             }
         } else {
             result = new Status(StatusCode.BADREQUEST, "Unknown action");
         }
 
-        return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result
-                .getDescription();
+        return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription();
     }
 
     @SuppressWarnings("unchecked")
     @RequestMapping(value = "/flow/deleteFlows", method = RequestMethod.POST)
     @ResponseBody
-    public String removeSelectedFlows(
-            @RequestParam(required = false) String body,
-            HttpServletRequest request,
+    public String removeSelectedFlows(@RequestParam(required = false) String body, HttpServletRequest request,
             @RequestParam(required = false) String container) {
-        String containerName = (container == null) ? GlobalConstants.DEFAULT
-                .toString() : container;
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
 
         // Authorization check
         String userName = request.getUserPrincipal().getName();
-        if (DaylightWebUtil
-                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return "Operation not authorized";
         }
-
-        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
-                .getInstance(IForwardingRulesManager.class, containerName, this);
+        IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance(
+                IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
             return "Forwarding Rules Manager is not available";
         }
@@ -343,26 +317,23 @@ public class Flows implements IDaylightWeb {
             Node node = Node.fromString(flowEntry.get("node"));
             result = frm.removeStaticFlow(flowEntry.get("name"), node);
             if (result.isSuccess()) {
-                DaylightWebUtil.auditlog("Flow", userName, "removed",
-                        flowEntry.get("name"), containerName);
+                DaylightWebUtil.auditlog("Flow Entry", userName, "removed", flowEntry.get("name") + " on Node "
+                        + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
             } else {
                 status = flowEntry.get("name") + ", " + status;
             }
         }
         if (!status.equals("")) {
-            return "Could not remove "
-                    + status.substring(0, status.length() - 2) + " Flow(s)";
+            return "Could not remove " + status.substring(0, status.length() - 2) + " Flow(s)";
         } else {
             return "Success";
         }
     }
 
     private String getNodeDesc(Node node, ISwitchManager switchManager) {
-        Description desc = (Description) switchManager.getNodeProp(node,
-                Description.propertyName);
+        Description desc = (Description) switchManager.getNodeProp(node, Description.propertyName);
         String description = (desc == null) ? "" : desc.getValue();
-        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node
-                .toString() : description;
+        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node.toString() : description;
     }
 
 }
index eafd8c54a773eb9bb933dd9f0d3f1cdd14d2b9c5..8c6e23f9d3c5b3243e9f842c2739ee67a78319ac 100644 (file)
@@ -46,6 +46,7 @@ public class DaylightWebAdmin {
     /**
      * Returns list of clustered controllers. Highlights "this" controller and
      * if controller is coordinator
+     *
      * @return List<ClusterBean>
      */
     @RequestMapping("/cluster")
@@ -68,17 +69,17 @@ public class DaylightWebAdmin {
         for (InetAddress controller : controllers) {
             ClusterNodeBean.Builder clusterBeanBuilder = new ClusterNodeBean.Builder(controller);
 
-            //get number of connected nodes
+            // get number of connected nodes
             Set<Node> connectedNodes = connectionManager.getNodes(controller);
             int numNodes = connectedNodes == null ? 0 : connectedNodes.size();
             clusterBeanBuilder.nodesConnected(numNodes);
 
-            //determine if this is the executing controller
+            // determine if this is the executing controller
             if (controller.equals(clusterServices.getMyAddress())) {
                 clusterBeanBuilder.highlightMe();
             }
 
-            //determine whether this is coordinator
+            // determine whether this is coordinator
             if (clusterServices.getCoordinatorAddress().equals(controller)) {
                 clusterBeanBuilder.iAmCoordinator();
             }
@@ -90,6 +91,7 @@ public class DaylightWebAdmin {
 
     /**
      * Return nodes connected to controller {controller}
+     *
      * @param controller
      *            - byte[] of the address of the controller
      * @return List<NodeBean>
@@ -179,7 +181,16 @@ public class DaylightWebAdmin {
         Status result = (action.equals("add")) ? userManager.addLocalUser(config) : userManager.removeLocalUser(config);
         if (result.isSuccess()) {
             String userAction = (action.equals("add")) ? "added" : "removed";
-            DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), userAction, config.getUser());
+            if (action.equals("add")) {
+                String userRoles = "";
+                for (String userRole : config.getRoles()) {
+                    userRoles = userRoles + userRole + ",";
+                }
+                DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), userAction, config.getUser()
+                        + " as " + userRoles.substring(0, userRoles.length() - 1));
+            } else {
+                DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), userAction, config.getUser());
+            }
             return "Success";
         }
         return result.getDescription();
@@ -269,13 +280,15 @@ public class DaylightWebAdmin {
         }
 
         if (status.isSuccess()) {
-            DaylightWebUtil.auditlog("User", requestingUser, "changed password for", username);
+            DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), " changed password for User ",
+                    username);
         }
         return status;
     }
 
     /**
      * Is the operation permitted for the given level
+     *
      * @param level
      */
     private boolean authorize(IUserManager userManager, UserLevel level, HttpServletRequest request) {
index 4435dcd58b987a6248977a1d7326f6069d34a0eb..6f0957790194681be581f27ad839b2707a314015 100644 (file)
@@ -2,8 +2,13 @@ package org.opendaylight.controller.web;
 
 import org.opendaylight.controller.containermanager.IContainerAuthorization;
 import org.opendaylight.controller.sal.authorization.Privilege;
+import org.opendaylight.controller.sal.core.Description;
+import org.opendaylight.controller.sal.core.Name;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
+import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.usermanager.IUserManager;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -74,4 +79,55 @@ public class DaylightWebUtil {
     public static void auditlog(String moduleName, String user, String action, String resource) {
         auditlog(moduleName, user, action, resource, null);
     }
+
+    public static String getNodeDesc(Node node, ISwitchManager switchManager) {
+        Description desc = (Description) switchManager.getNodeProp(node,
+                Description.propertyName);
+        String description = (desc == null) ? "" : desc.getValue();
+        return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node
+                .toString() : description;
+    }
+
+    public static String getNodeDesc(Node node, String containerName,
+            Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class, containerName, bundle);
+        if (switchManager == null) {
+            return null;
+        }
+
+        return getNodeDesc(node, switchManager);
+    }
+
+    public static String getNodeDesc(Node node, Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class,
+                        GlobalConstants.DEFAULT.toString(), bundle);
+        if (switchManager == null) {
+            return null;
+        }
+
+        return getNodeDesc(node, switchManager);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector,
+            String container, Object bundle) {
+        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                .getInstance(ISwitchManager.class, container, bundle);
+        return getPortName(nodeConnector, switchManager);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector, Object bundle) {
+        return getPortName(nodeConnector, GlobalConstants.DEFAULT.toString(), bundle);
+    }
+
+    public static String getPortName(NodeConnector nodeConnector,
+            ISwitchManager switchManager) {
+        Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
+                Name.NamePropName));
+        String nodeConnectorName = (ncName != null) ? ncName.getValue() : nodeConnector.getNodeConnectorIdAsString();
+        nodeConnectorName = nodeConnectorName + "@"
+                + getNodeDesc(nodeConnector.getNode(), switchManager);
+        return nodeConnectorName.substring(0, nodeConnectorName.length());
+    }
 }
\ No newline at end of file
index a6c390d799bb1fa54ac1329436ab2a3b47d2b037..f6a05882833ccc2f03851405f57e2b5480e159d4 100644 (file)
@@ -114,6 +114,7 @@ public class Topology implements IObjectReader, IConfigurationAware {
         Map<Node, Set<Edge>> nodeEdges = topologyManager.getNodeEdges();
         Map<Node, Set<NodeConnector>> hostEdges = topologyManager
                 .getNodesWithNodeConnectorHost();
+        int hostEdgesHashCode = getHostHashCode(hostEdges, topologyManager);
         List<Switch> nodes = switchManager.getNetworkDevices();
 
         List<SwitchConfig> switchConfigurations = new ArrayList<SwitchConfig>();
@@ -136,14 +137,14 @@ public class Topology implements IObjectReader, IConfigurationAware {
         // return cache if topology hasn't changed
         if (
                 (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
-                metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
+                metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdgesHashCode) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
         ) {
                 return metaCache.get(containerName).values();
         }
 
         // cache has changed, we must assign the new values
         metaNodeHash.put(containerName, nodeEdges.hashCode());
-        metaHostHash.put(containerName, hostEdges.hashCode());
+        metaHostHash.put(containerName, hostEdgesHashCode);
         metaNodeSingleHash.put(containerName, nodes.hashCode());
         metaNodeConfigurationHash.put(containerName, switchConfigurations.hashCode());
 
@@ -330,6 +331,29 @@ public class Topology implements IObjectReader, IConfigurationAware {
         }
     }
 
+    /**
+     * Calculate the total host hashcode
+     *
+     * This is to handle cases where there are multiple hosts per NodeConnector
+     *
+     * @param hostEdges
+     *            - hostEdges data structure
+     * @param topology
+     *            - topology bundle
+     * @return this topology's host hashcode
+     */
+    private int getHostHashCode(Map<Node, Set<NodeConnector>> hostEdges, ITopologyManager topology) {
+        List<Host> hosts = new ArrayList<Host>();
+        for (Set<NodeConnector> nodeConnectors : hostEdges.values()) {
+            for (NodeConnector nodeConnector : nodeConnectors) {
+                List<Host> theseHosts = topology.getHostsAttachedToNodeConnector(nodeConnector);
+                hosts.addAll(theseHosts);
+            }
+        }
+
+        return hosts.hashCode();
+    }
+
     /**
      * Add regular hosts to main topology
      *
index bcf911f0a5583a46bf14b5150ff20a01c1096bfc..a8b6860d10926cce6c925131948626ce573e6dad 100644 (file)
@@ -90,13 +90,10 @@ one.f.troubleshooting.existingNodes = {
             modal: "one_f_troubleshooting_existingNodes_id_modal",
             existingNodesDataGrid: "one_f_troubleshooting_existingNodes_id_datagrid",
             portsDataGrid: "one_f_troubleshooting_existingNodes_id_portsDataGrid",
-            flowsDataGrid: "one_f_troubleshooting_existingNodes_id_flowsDataGrid"
-        },
-        // TODO: Make these values configurable.
-        autoRefreshInterval: {
-            flows: 10000,
-            ports: 10000,
-            refreshRateInterval: 5000
+            flowsDataGrid: "one_f_troubleshooting_existingNodes_id_flowsDataGrid",
+            refreshFlowsButton:"one_f_troubleshooting_existingNodes_id_refreshFlowsButton",
+            refreshPortsButton:"one_f_troubleshooting_existingNodes_id_refreshPortsButton"
+
         },
         load: {
             main: function($dashlet) {
@@ -122,13 +119,18 @@ one.f.troubleshooting.existingNodes = {
                     if(one.f.troubleshooting === undefined){
                         return;
                     }
-                    clearTimeout(one.f.troubleshooting.existingNodes.registry.refreshTimer);
                     $.getJSON(one.main.constants.address.prefix + "/troubleshoot/flowStats?nodeId=" + nodeId, function(content) {
                         $rightBottomDashlet = one.f.troubleshooting.rightBottomDashlet.get();
                         one.f.troubleshooting.rightBottomDashlet.setDashletHeader("Flows");
                         one.lib.dashlet.empty($rightBottomDashlet);
                         $rightBottomDashlet.append(one.lib.dashlet.header("Flow Details"));
-
+                        var button = one.lib.dashlet.button.single("Refresh",
+                                one.f.troubleshooting.existingNodes.id.refreshFlowsButton, "btn-primary", "btn-mini");
+                        var $button = one.lib.dashlet.button.button(button);
+                        $button.click(function() {
+                            one.f.troubleshooting.existingNodes.load.flows(nodeId);
+                        });
+                        $rightBottomDashlet.append($button);
                         var $gridHTML = one.lib.dashlet.datagrid.init(one.f.troubleshooting.existingNodes.id.flowsDataGrid, {
                             searchable: true,
                             filterable: false,
@@ -138,16 +140,6 @@ one.f.troubleshooting.existingNodes = {
                         $rightBottomDashlet.append($gridHTML);
                         var dataSource = one.f.troubleshooting.existingNodes.data.flowsGrid(content);
                         $("#" + one.f.troubleshooting.existingNodes.id.flowsDataGrid).datagrid({dataSource: dataSource});
-
-                        var numberOfFlows = content.nodeData.length;
-                        var refreshRate = one.f.troubleshooting.existingNodes.autoRefreshInterval.flows;
-                        if (numberOfFlows > 0) {
-                            refreshRate += Math.floor(numberOfFlows / 500) *
-                                one.f.troubleshooting.existingNodes.autoRefreshInterval.refreshRateInterval;
-                        }
-                        one.f.troubleshooting.existingNodes.registry.refreshTimer = setTimeout(
-                                one.f.troubleshooting.existingNodes.load.flows,
-                                refreshRate, nodeId);
                     });
                 } catch(e) {}
             },
@@ -156,13 +148,18 @@ one.f.troubleshooting.existingNodes = {
                     if(one.f.troubleshooting === undefined){
                         return;
                     }
-                    clearTimeout(one.f.troubleshooting.existingNodes.registry.refreshTimer);
                     $.getJSON(one.main.constants.address.prefix + "/troubleshoot/portStats?nodeId=" + nodeId, function(content) {
                         $rightBottomDashlet = one.f.troubleshooting.rightBottomDashlet.get();
                         one.f.troubleshooting.rightBottomDashlet.setDashletHeader("Ports");
                         one.lib.dashlet.empty($rightBottomDashlet);
                         $rightBottomDashlet.append(one.lib.dashlet.header("Port Details"));
-
+                        var button = one.lib.dashlet.button.single("Refresh",
+                                one.f.troubleshooting.existingNodes.id.refreshPortsButton, "btn-primary", "btn-mini");
+                        var $button = one.lib.dashlet.button.button(button);
+                        $button.click(function() {
+                            one.f.troubleshooting.existingNodes.load.ports(nodeId);
+                        });
+                        $rightBottomDashlet.append($button);
                         var $gridHTML = one.lib.dashlet.datagrid.init(one.f.troubleshooting.existingNodes.id.portsDataGrid, {
                             searchable: true,
                             filterable: false,
@@ -172,16 +169,6 @@ one.f.troubleshooting.existingNodes = {
                         $rightBottomDashlet.append($gridHTML);
                         var dataSource = one.f.troubleshooting.existingNodes.data.portsGrid(content);
                         $("#" + one.f.troubleshooting.existingNodes.id.portsDataGrid).datagrid({dataSource: dataSource});
-
-                        var numberOfPorts = content.nodeData.length;
-                        var refreshRate = one.f.troubleshooting.existingNodes.autoRefreshInterval.ports;
-                        if (numberOfPorts > 0) {
-                            refreshRate += Math.floor(numberOfPorts / 500) *
-                                one.f.troubleshooting.existingNodes.autoRefreshInterval.refreshRateInterval;
-                        }
-                        one.f.troubleshooting.existingNodes.registry.refreshTimer = setTimeout(
-                                one.f.troubleshooting.existingNodes.load.ports,
-                                refreshRate, nodeId);
                     });
                 } catch(e) {}
             } 
@@ -296,7 +283,7 @@ one.f.troubleshooting.existingNodes = {
                         }
                     ],
                     data: data.nodeData,
-                    delay: 200
+                    delay: 0
                 });
                 return source;
             },