Fix exception handling in neutronvpn shell 93/63193/2
authorMichael Vorburger <vorburger@redhat.com>
Wed, 13 Sep 2017 17:56:57 +0000 (19:56 +0200)
committerSam Hague <shague@redhat.com>
Sun, 17 Sep 2017 22:17:30 +0000 (22:17 +0000)
see
https://wiki.opendaylight.org/view/BestPractices/Coding_Guidelines#IllegalCatch

motivated by/while reviewing
https://git.opendaylight.org/gerrit/#/c/62711/3/vpnservice/neutronvpn/neutronvpn-impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronvpnManager.java

Change-Id: I8ebc913e66d2fe33ffadf361214bb82263aec149
Signed-off-by: Michael Vorburger <vorburger@redhat.com>
(cherry picked from commit 72bef67d06d2793aee07979d6ef0df7d715115f0)

vpnservice/neutronvpn/neutronvpn-api/src/main/java/org/opendaylight/netvirt/neutronvpn/interfaces/INeutronVpnManager.java
vpnservice/neutronvpn/neutronvpn-impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronvpnManager.java
vpnservice/neutronvpn/neutronvpn-impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronvpnManagerImpl.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/ConfigureL3VpnCommand.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/DhcpConfigureCommand.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/DhcpShowCommand.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/ShowNeutronPortsCommand.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/ShowSubnet.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/ShowVpnConfigCommand.java
vpnservice/neutronvpn/neutronvpn-shell/src/main/java/org/opendaylight/netvirt/neutronvpn/shell/ShowVpnIpToPort.java

index 15975d5849816a747baf9efd13233bf3431bfc0b..8fc193767073add1e1965eb42bb26fb5406b2085 100644 (file)
@@ -10,6 +10,8 @@ package org.opendaylight.netvirt.neutronvpn.interfaces;
 
 import java.util.Collection;
 import java.util.List;
+import java.util.concurrent.ExecutionException;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
@@ -22,9 +24,9 @@ public interface INeutronVpnManager {
 
     void removeSubnetFromVpn(Uuid vpnId, Uuid subnet);
 
-    List<String> showVpnConfigCLI(Uuid vuuid);
+    List<String> showVpnConfigCLI(Uuid vuuid) throws InterruptedException, ExecutionException;
 
-    List<String> showNeutronPortsCLI();
+    List<String> showNeutronPortsCLI() throws ReadFailedException;
 
     Network getNeutronNetwork(Uuid networkId);
 
index 68804838ff1db464a038b5447fc82203780b1e5c..281377d91ce9a9ca7c9bd4b439dd3e0cf046ebad 100644 (file)
@@ -7,6 +7,9 @@
  */
 package org.opendaylight.netvirt.neutronvpn;
 
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+import static org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker.syncReadOptional;
+
 import com.google.common.base.Optional;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
@@ -31,6 +34,7 @@ import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.genius.datastoreutils.DataStoreJobCoordinator;
 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
@@ -147,7 +151,9 @@ import org.slf4j.LoggerFactory;
 
 @Singleton
 public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, EventListener {
+
     private static final Logger LOG = LoggerFactory.getLogger(NeutronvpnManager.class);
+
     private final DataBroker dataBroker;
     private final NeutronvpnNatManager nvpnNatManager;
     private final NotificationPublishService notificationPublishService;
@@ -698,7 +704,7 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
         for (FixedIps ip : ips) {
             // create vm adjacency
             String ipValue = String.valueOf(ip.getIpAddress().getValue());
-            String ipPrefix = (ip.getIpAddress().getIpv4Address() != null) ? ipValue + "/32" : ipValue + "/128";
+            String ipPrefix = ip.getIpAddress().getIpv4Address() != null ? ipValue + "/32" : ipValue + "/128";
             Adjacency vmAdj = new AdjacencyBuilder().setKey(new AdjacencyKey(ipPrefix)).setIpAddress(ipPrefix)
                     .setMacAddress(port.getMacAddress().getValue()).setAdjacencyType(AdjacencyType.PrimaryAdjacency)
                     .setSubnetId(ip.getSubnetId()).build();
@@ -774,7 +780,7 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
                 LOG.debug("Updating vpn interface {}", infName);
                 if (!isBeingAssociated) {
                     Adjacencies adjs = vpnIfBuilder.getAugmentation(Adjacencies.class);
-                    List<Adjacency> adjacencyList = (adjs != null) ? adjs.getAdjacency() : new ArrayList<>();
+                    List<Adjacency> adjacencyList = adjs != null ? adjs.getAdjacency() : new ArrayList<>();
                     Iterator<Adjacency> adjacencyIter = adjacencyList.iterator();
                     while (adjacencyIter.hasNext()) {
                         Adjacency adjacency = adjacencyIter.next();
@@ -1404,10 +1410,10 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
     private boolean isNexthopTheOtherVpnLinkEndpoint(String nexthop, String thisVpnUuid, InterVpnLink interVpnLink) {
         return
                 interVpnLink != null
-                        && ((interVpnLink.getFirstEndpoint().getVpnUuid().getValue().equals(thisVpnUuid)
-                        && interVpnLink.getSecondEndpoint().getIpAddress().getValue().equals(nexthop))
-                        || (interVpnLink.getSecondEndpoint().getVpnUuid().getValue().equals(thisVpnUuid)
-                        && interVpnLink.getFirstEndpoint().getIpAddress().getValue().equals(nexthop)));
+                        && (interVpnLink.getFirstEndpoint().getVpnUuid().getValue().equals(thisVpnUuid)
+                        && interVpnLink.getSecondEndpoint().getIpAddress().getValue().equals(nexthop)
+                        || interVpnLink.getSecondEndpoint().getVpnUuid().getValue().equals(thisVpnUuid)
+                        && interVpnLink.getFirstEndpoint().getIpAddress().getValue().equals(nexthop));
     }
 
     protected List<Adjacency> getAdjacencyforExtraRoute(Uuid vpnId, List<Routes> routeList, String fixedIp) {
@@ -1563,7 +1569,7 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
     public void removeVpn(Uuid id) {
         // read VPNMaps
         VpnMap vpnMap = NeutronvpnUtils.getVpnMap(dataBroker, id);
-        Uuid router = (vpnMap != null) ? vpnMap.getRouterId() : null;
+        Uuid router = vpnMap != null ? vpnMap.getRouterId() : null;
         // dissociate router
         if (router != null) {
             dissociateRouterFromVpn(id, router);
@@ -1708,7 +1714,7 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
                     failedNwList.add(String.format("network %s already associated to another VPN %s", nw.getValue(),
                             vpnId.getValue()));
                 } else if (isVpnOfTypeL2(vpnInstance)
-                        && (neutronEvpnUtils.isVpnAssociatedWithNetwork(vpnInstance))) {
+                        && neutronEvpnUtils.isVpnAssociatedWithNetwork(vpnInstance)) {
                     LOG.error("EVPN supports only one network to be associated");
                     failedNwList.add(String.format("EVPN supports only one network to be associated"));
                 } else {
@@ -2089,51 +2095,39 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
      * Implementation of the "vpnservice:neutron-ports-show" Karaf CLI command.
      *
      * @return a List of String to be printed on screen
+     * @throws ReadFailedException if there was a problem reading from the data store
      */
-    // TODO Clean up the exception handling and the console output
-    @SuppressWarnings({"checkstyle:IllegalCatch", "checkstyle:RegexpSinglelineJava"})
-    public List<String> showNeutronPortsCLI() {
+    public List<String> showNeutronPortsCLI() throws ReadFailedException {
         List<String> result = new ArrayList<>();
         result.add(String.format(" %-36s  %-19s  %-13s  %-20s ", "Port ID", "Mac Address", "Prefix Length",
             "IP Address"));
         result.add("-------------------------------------------------------------------------------------------");
         InstanceIdentifier<Ports> portidentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
-        try {
-            Optional<Ports> ports =
-                NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION, portidentifier);
-            if (ports.isPresent() && ports.get().getPort() != null) {
-                for (Port port : ports.get().getPort()) {
-                    List<FixedIps> fixedIPs = port.getFixedIps();
-                    try {
-                        if (fixedIPs != null && !fixedIPs.isEmpty()) {
-                            List<String> ipList = new ArrayList<>();
-                            for (FixedIps fixedIp : fixedIPs) {
-                                IpAddress ipAddress = fixedIp.getIpAddress();
-                                if (ipAddress.getIpv4Address() != null) {
-                                    ipList.add(ipAddress.getIpv4Address().getValue());
-                                } else {
-                                    ipList.add((ipAddress.getIpv6Address().getValue()));
-                                }
-                            }
-                            result.add(String.format(" %-36s  %-19s  %-13s  %-20s ", port.getUuid().getValue(), port
-                                    .getMacAddress().getValue(), NeutronvpnUtils.getIPPrefixFromPort(dataBroker, port),
-                                    ipList.toString()));
+
+        Optional<Ports> ports = syncReadOptional(dataBroker, CONFIGURATION, portidentifier);
+        if (ports.isPresent() && ports.get().getPort() != null) {
+            for (Port port : ports.get().getPort()) {
+                List<FixedIps> fixedIPs = port.getFixedIps();
+                if (fixedIPs != null && !fixedIPs.isEmpty()) {
+                    List<String> ipList = new ArrayList<>();
+                    for (FixedIps fixedIp : fixedIPs) {
+                        IpAddress ipAddress = fixedIp.getIpAddress();
+                        if (ipAddress.getIpv4Address() != null) {
+                            ipList.add(ipAddress.getIpv4Address().getValue());
                         } else {
-                            result.add(String.format(" %-36s  %-19s  %-13s  %-20s ", port.getUuid().getValue(), port
-                                    .getMacAddress().getValue(), "Not Assigned", "Not Assigned"));
+                            ipList.add(ipAddress.getIpv6Address().getValue());
                         }
-                    } catch (Exception e) {
-                        LOG.error("Failed to retrieve neutronPorts info for port {}: ", port.getUuid().getValue(),
-                                e);
-                        System.out.println("Failed to retrieve neutronPorts info for port: " + port.getUuid()
-                                .getValue() + ": " + e.getMessage());
                     }
+                    result.add(String.format(" %-36s  %-19s  %-13s  %-20s ", port.getUuid().getValue(), port
+                            .getMacAddress().getValue(), NeutronvpnUtils.getIPPrefixFromPort(dataBroker, port),
+                            ipList.toString()));
+                } else {
+                    result.add(String.format(" %-36s  %-19s  %-13s  %-20s ", port.getUuid().getValue(), port
+                            .getMacAddress().getValue(), "Not Assigned", "Not Assigned"));
                 }
             }
-        } catch (Exception e) {
-            LOG.error("Failed to retrieve neutronPorts info : ", e);
-            System.out.println("Failed to retrieve neutronPorts info : " + e.getMessage());
         }
+
         return result;
     }
 
@@ -2142,72 +2136,68 @@ public class NeutronvpnManager implements NeutronvpnService, AutoCloseable, Even
      *
      * @param vpnuuid Uuid of the VPN whose config must be shown
      * @return formatted output list
+     * @throws InterruptedException if there was a thread related problem getting the data to display
+     * @throws ExecutionException if there was any other problem getting the data to display
      */
-    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
-    public List<String> showVpnConfigCLI(Uuid vpnuuid) {
+    public List<String> showVpnConfigCLI(Uuid vpnuuid) throws InterruptedException, ExecutionException {
         List<String> result = new ArrayList<>();
         if (vpnuuid == null) {
-            System.out.println("");
-            System.out.println("Displaying VPN config for all VPNs");
-            System.out.println("To display VPN config for a particular VPN, use the following syntax");
-            System.out.println(getshowVpnConfigCLIHelp());
-        }
-        try {
-            RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
-            if (rpcResult.isSuccessful()) {
+            result.add("");
+            result.add("Displaying VPN config for all VPNs");
+            result.add("To display VPN config for a particular VPN, use the following syntax");
+            result.add(getshowVpnConfigCLIHelp());
+        }
+        RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
+        if (rpcResult.isSuccessful()) {
+            result.add("");
+            result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
+            result.add("");
+            result.add(String.format(" %-80s ", "Import-RTs"));
+            result.add("");
+            result.add(String.format(" %-80s ", "Export-RTs"));
+            result.add("");
+            result.add(String.format(" %-76s ", "Subnet IDs"));
+            result.add("");
+            result.add("------------------------------------------------------------------------------------");
+            result.add("");
+            List<L3vpnInstances> vpnList = rpcResult.getResult().getL3vpnInstances();
+            for (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn
+                        .rev150602.VpnInstance vpn : vpnList) {
+                String tenantId = vpn.getTenantId() != null ? vpn.getTenantId().getValue()
+                        : "\"                 " + "                  \"";
+                result.add(String.format(" %-37s %-37s %-7s ", vpn.getId().getValue(), tenantId,
+                        vpn.getRouteDistinguisher()));
                 result.add("");
-                result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
+                result.add(String.format(" %-80s ", vpn.getImportRT()));
                 result.add("");
-                result.add(String.format(" %-80s ", "Import-RTs"));
+                result.add(String.format(" %-80s ", vpn.getExportRT()));
                 result.add("");
-                result.add(String.format(" %-80s ", "Export-RTs"));
+
+                Uuid vpnid = vpn.getId();
+                List<Uuid> subnetList = NeutronvpnUtils.getSubnetsforVpn(dataBroker, vpnid);
+                if (!subnetList.isEmpty()) {
+                    for (Uuid subnetuuid : subnetList) {
+                        result.add(String.format(" %-76s ", subnetuuid.getValue()));
+                    }
+                } else {
+                    result.add(String.format(" %-76s ", "\"                                    \""));
+                }
                 result.add("");
-                result.add(String.format(" %-76s ", "Subnet IDs"));
+                result.add("----------------------------------------");
                 result.add("");
-                result.add("------------------------------------------------------------------------------------");
+            }
+        } else {
+            String errortag = rpcResult.getErrors().iterator().next().getTag();
+            if (Objects.equals(errortag, "")) {
                 result.add("");
-                List<L3vpnInstances> vpnList = rpcResult.getResult().getL3vpnInstances();
-                for (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn
-                            .rev150602.VpnInstance vpn : vpnList) {
-                    String tenantId = vpn.getTenantId() != null ? vpn.getTenantId().getValue()
-                            : "\"                 " + "                  \"";
-                    result.add(String.format(" %-37s %-37s %-7s ", vpn.getId().getValue(), tenantId,
-                            vpn.getRouteDistinguisher()));
-                    result.add("");
-                    result.add(String.format(" %-80s ", vpn.getImportRT()));
-                    result.add("");
-                    result.add(String.format(" %-80s ", vpn.getExportRT()));
-                    result.add("");
-
-                    Uuid vpnid = vpn.getId();
-                    List<Uuid> subnetList = NeutronvpnUtils.getSubnetsforVpn(dataBroker, vpnid);
-                    if (!subnetList.isEmpty()) {
-                        for (Uuid subnetuuid : subnetList) {
-                            result.add(String.format(" %-76s ", subnetuuid.getValue()));
-                        }
-                    } else {
-                        result.add(String.format(" %-76s ", "\"                                    \""));
-                    }
-                    result.add("");
-                    result.add("----------------------------------------");
-                    result.add("");
-                }
+                result.add("No VPN has been configured yet");
+            } else if (Objects.equals(errortag, "invalid-value")) {
+                result.add("");
+                result.add("VPN " + vpnuuid.getValue() + " is not present");
             } else {
-                String errortag = rpcResult.getErrors().iterator().next().getTag();
-                if (Objects.equals(errortag, "")) {
-                    System.out.println("");
-                    System.out.println("No VPN has been configured yet");
-                } else if (Objects.equals(errortag, "invalid-value")) {
-                    System.out.println("");
-                    System.out.println("VPN " + vpnuuid.getValue() + " is not present");
-                } else {
-                    System.out.println("error getting VPN info : " + rpcResult.getErrors());
-                    System.out.println(getshowVpnConfigCLIHelp());
-                }
+                result.add("error getting VPN info : " + rpcResult.getErrors());
+                result.add(getshowVpnConfigCLIHelp());
             }
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("error getting VPN info for VPN {}: ", vpnuuid.getValue(), e);
-            System.out.println("error getting VPN info : " + e.getMessage());
         }
         return result;
     }
index d1f7ad50de45e2882d8d77c4bb307df3fd6e67e5..14bfcb69e8780dfb49aeb830fa0657366965b5c7 100644 (file)
@@ -9,8 +9,10 @@ package org.opendaylight.netvirt.neutronvpn;
 
 import java.util.Collection;
 import java.util.List;
+import java.util.concurrent.ExecutionException;
 import javax.inject.Inject;
 import javax.inject.Singleton;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.netvirt.neutronvpn.interfaces.INeutronVpnManager;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
@@ -21,7 +23,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.s
 @Singleton
 public class NeutronvpnManagerImpl implements INeutronVpnManager {
 
-    private NeutronvpnManager nvManager;
+    private final NeutronvpnManager nvManager;
 
     @Inject
     public NeutronvpnManagerImpl(final NeutronvpnManager neutronvpnManager) {
@@ -29,7 +31,7 @@ public class NeutronvpnManagerImpl implements INeutronVpnManager {
     }
 
     @Override
-    public List<String> showNeutronPortsCLI() {
+    public List<String> showNeutronPortsCLI() throws ReadFailedException {
         return nvManager.showNeutronPortsCLI();
     }
 
@@ -39,7 +41,7 @@ public class NeutronvpnManagerImpl implements INeutronVpnManager {
     }
 
     @Override
-    public List<String> showVpnConfigCLI(Uuid vuuid) {
+    public List<String> showVpnConfigCLI(Uuid vuuid) throws InterruptedException, ExecutionException {
         return nvManager.showVpnConfigCLI(vuuid);
     }
 
index 77eed95b3a8d05a31070c68a5deb994d84045863..e02c86f30a74a53b69af220e81c76d81a921c4b0 100644 (file)
@@ -5,7 +5,6 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.netvirt.neutronvpn.shell;
 
 import java.util.ArrayList;
@@ -38,6 +37,7 @@ import org.slf4j.LoggerFactory;
 public class ConfigureL3VpnCommand extends OsgiCommandSupport {
 
     private static final Logger LOG = LoggerFactory.getLogger(ConfigureL3VpnCommand.class);
+
     private INeutronVpnManager neutronVpnManager;
     private RpcProviderRegistry rpcProviderRegistry;
     private NeutronvpnService neutronvpnService;
@@ -81,7 +81,6 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
 
     @Override
     protected Object doExecute() throws Exception {
-
         if (rpcProviderRegistry != null) {
             neutronvpnService = rpcProviderRegistry.getRpcService(NeutronvpnService.class);
             if (neutronvpnService != null) {
@@ -111,10 +110,7 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
         return null;
     }
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    public void createL3VpnCLI() {
-
+    private void createL3VpnCLI() throws InterruptedException, ExecutionException {
         if (vid == null) {
             session.getConsole().println("Please supply a valid VPN ID");
             session.getConsole().println(getHelp("create"));
@@ -142,7 +138,7 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
         Uuid vuuid = new Uuid(vid);
 
         RpcResult<CreateL3VPNOutput> createL3VpnRpcResult = null;
-        try {
+        {
             ArrayList<String> rdList = new ArrayList<>(Arrays.asList(rd.split(",")));
             ArrayList<String> irtList = new ArrayList<>(Arrays.asList(irt.split(",")));
             ArrayList<String> ertList = new ArrayList<>(Arrays.asList(ert.split(",")));
@@ -166,10 +162,6 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
                 session.getConsole().println("Error populating createL3VPN : " + result.get().getErrors());
                 session.getConsole().println(getHelp("create"));
             }
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("error populating createL3VPN for VPN ID {}", vid, e);
-            session.getConsole().println("Error populating createL3VPN : " + e.getMessage());
-            session.getConsole().println(getHelp("create"));
         }
 
         /**
@@ -177,7 +169,7 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
          * association of network(s) to VPN is being intended.
          */
         if (createL3VpnRpcResult.isSuccessful()) {
-            try {
+            {
                 List<Uuid> networkIdList = new ArrayList<>();
 
                 if (sid != null) {
@@ -207,18 +199,11 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
                         }
                     }
                 }
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.error("error while adding subnet(s) to VPN {}", vid, e);
-                session.getConsole().println("Error while adding subnet(s) to VPN: " + e.getMessage());
-                session.getConsole().println(getHelp("create"));
             }
         }
     }
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    public void deleteL3VpnCLI() {
-
+    private void deleteL3VpnCLI() throws InterruptedException, ExecutionException {
         if (vid == null) {
             session.getConsole().println("Please supply a valid VPN ID");
             session.getConsole().println(getHelp("delete"));
@@ -229,47 +214,35 @@ public class ConfigureL3VpnCommand extends OsgiCommandSupport {
         // disassociation of network(s) (removal of subnet(s)) from VPN to be followed by deletion of VPN
         RpcResult<DissociateNetworksOutput> dissociateNetworksRpcResult = null;
         List<Uuid> networkIdList = null;
-        try {
-            networkIdList = neutronVpnManager.getNetworksForVpn(vpnId);
-
-            if (networkIdList != null && !networkIdList.isEmpty()) {
-                Future<RpcResult<DissociateNetworksOutput>> result =
-                        neutronvpnService.dissociateNetworks(new DissociateNetworksInputBuilder()
-                                .setVpnId(vpnId).setNetworkId(networkIdList).build());
-                dissociateNetworksRpcResult = result.get();
-                if (dissociateNetworksRpcResult.isSuccessful()) {
-                    session.getConsole().println("Subnet(s) removed from VPN successfully");
-                    LOG.trace("dissociateNetworks: {}", result);
-                } else {
-                    session.getConsole().println("Error while removing subnet(s) from VPN: "
-                            + result.get().getErrors());
-                    session.getConsole().println(getHelp("delete"));
-                }
+        networkIdList = neutronVpnManager.getNetworksForVpn(vpnId);
+
+        if (networkIdList != null && !networkIdList.isEmpty()) {
+            Future<RpcResult<DissociateNetworksOutput>> result =
+                    neutronvpnService.dissociateNetworks(new DissociateNetworksInputBuilder()
+                            .setVpnId(vpnId).setNetworkId(networkIdList).build());
+            dissociateNetworksRpcResult = result.get();
+            if (dissociateNetworksRpcResult.isSuccessful()) {
+                session.getConsole().println("Subnet(s) removed from VPN successfully");
+                LOG.trace("dissociateNetworks: {}", result);
+            } else {
+                session.getConsole().println("Error while removing subnet(s) from VPN: "
+                        + result.get().getErrors());
+                session.getConsole().println(getHelp("delete"));
             }
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("error while adding removing subnet(s) from VPN {}", vid, e);
-            session.getConsole().println("Error while removing subnet(s) from VPN: " + e.getMessage());
-            session.getConsole().println(getHelp("delete"));
         }
 
         if (networkIdList == null || networkIdList.isEmpty() || dissociateNetworksRpcResult.isSuccessful()) {
-            try {
-                List<Uuid> vpnIdList = new ArrayList<>();
-                vpnIdList.add(vpnId);
-
-                Future<RpcResult<DeleteL3VPNOutput>> result =
-                        neutronvpnService.deleteL3VPN(new DeleteL3VPNInputBuilder().setId(vpnIdList).build());
-                RpcResult<DeleteL3VPNOutput> rpcResult = result.get();
-                if (rpcResult.isSuccessful()) {
-                    session.getConsole().println("L3VPN deleted successfully");
-                    LOG.trace("deletel3vpn: {}", result);
-                } else {
-                    session.getConsole().println("Error populating deleteL3VPN : " + result.get().getErrors());
-                    session.getConsole().println(getHelp("delete"));
-                }
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.error("error populating deleteL3VPN for VPN ID {}", vid, e);
-                session.getConsole().println("Error populating deleteL3VPN : " + e.getMessage());
+            List<Uuid> vpnIdList = new ArrayList<>();
+            vpnIdList.add(vpnId);
+
+            Future<RpcResult<DeleteL3VPNOutput>> result =
+                    neutronvpnService.deleteL3VPN(new DeleteL3VPNInputBuilder().setId(vpnIdList).build());
+            RpcResult<DeleteL3VPNOutput> rpcResult = result.get();
+            if (rpcResult.isSuccessful()) {
+                session.getConsole().println("L3VPN deleted successfully");
+                LOG.trace("deletel3vpn: {}", result);
+            } else {
+                session.getConsole().println("Error populating deleteL3VPN : " + result.get().getErrors());
                 session.getConsole().println(getHelp("delete"));
             }
         } else {
index 34cef1fa8b72170f9987eed9442bda0eddad61dd..a27cc1b3b1b64496eaf3ccd38c1680e3b9cb17eb 100644 (file)
@@ -8,20 +8,15 @@
 
 package org.opendaylight.netvirt.neutronvpn.shell;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+
 import java.util.Collections;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
-
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.commands.Option;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
 import org.opendaylight.netvirt.dhcpservice.api.DhcpMConstants;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.DhcpConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.DhcpConfigBuilder;
@@ -51,80 +46,41 @@ public class DhcpConfigureCommand extends OsgiCommandSupport {
     }
 
     @Override
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
     protected Object doExecute() throws Exception {
-        try {
-            if ((defaultDomain == null) && (leaseDuration == null)) {
-                session.getConsole().println(getHelp());
-                return null;
+        if (defaultDomain == null && leaseDuration == null) {
+            session.getConsole().println(getHelp());
+            return null;
+        }
+        Integer currLeaseDuration = DhcpMConstants.DEFAULT_LEASE_TIME;
+        String currDefDomain = DhcpMConstants.DEFAULT_DOMAIN_NAME;
+        ConfigsBuilder dccBuilder = new ConfigsBuilder();
+        InstanceIdentifier<DhcpConfig> iid = InstanceIdentifier.create(DhcpConfig.class);
+        DhcpConfig currentConfig = SingleTransactionDataBroker.syncRead(dataBroker, CONFIGURATION, iid);
+        if (currentConfig != null && currentConfig.getConfigs() != null
+            && !currentConfig.getConfigs().isEmpty()) {
+            Configs dhcpConfig = currentConfig.getConfigs().get(0);
+            if (dhcpConfig.getLeaseDuration() != null) {
+                currLeaseDuration = dhcpConfig.getLeaseDuration();
             }
-            Integer currLeaseDuration = DhcpMConstants.DEFAULT_LEASE_TIME;
-            String currDefDomain = DhcpMConstants.DEFAULT_DOMAIN_NAME;
-            ConfigsBuilder dccBuilder = new ConfigsBuilder();
-            InstanceIdentifier<DhcpConfig> iid = InstanceIdentifier.create(DhcpConfig.class);
-            DhcpConfig currentConfig = read(iid);
-            if (currentConfig != null && currentConfig.getConfigs() != null
-                && !currentConfig.getConfigs().isEmpty()) {
-                Configs dhcpConfig = currentConfig.getConfigs().get(0);
-                if (dhcpConfig.getLeaseDuration() != null) {
-                    currLeaseDuration = dhcpConfig.getLeaseDuration();
-                }
-                if (dhcpConfig.getDefaultDomain() != null) {
-                    currDefDomain = dhcpConfig.getDefaultDomain();
-                }
+            if (dhcpConfig.getDefaultDomain() != null) {
+                currDefDomain = dhcpConfig.getDefaultDomain();
             }
-
-            dccBuilder.setLeaseDuration((leaseDuration == null) ? currLeaseDuration : leaseDuration);
-            dccBuilder.setDefaultDomain((defaultDomain == null) ? currDefDomain : defaultDomain);
-
-            List<Configs> configList = Collections.singletonList(dccBuilder.build());
-            DhcpConfigBuilder dcBuilder = new DhcpConfigBuilder();
-            dcBuilder.setConfigs(configList);
-            write(iid, dcBuilder.build());
-        } catch (Exception e) {
-            session.getConsole().println("Failed to configure. Try again");
-            LOG.error("Failed to configure DHCP parameters", e);
         }
-        return null;
-    }
 
-    private void write(InstanceIdentifier<DhcpConfig> iid, DhcpConfig dhcpConfig) {
-        WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
-        tx.put(LogicalDatastoreType.CONFIGURATION, iid, dhcpConfig);
-        CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
-        try {
-            futures.get();
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error writing to datastore (path, data) : ({}, {})", iid, dhcpConfig);
-            throw new RuntimeException(e.getMessage());
-        }
-    }
+        dccBuilder.setLeaseDuration(leaseDuration == null ? currLeaseDuration : leaseDuration);
+        dccBuilder.setDefaultDomain(defaultDomain == null ? currDefDomain : defaultDomain);
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    private DhcpConfig read(InstanceIdentifier<DhcpConfig> iid) {
-
-        ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
-        Optional<DhcpConfig> result = Optional.absent();
-        try {
-            result = tx.read(LogicalDatastoreType.CONFIGURATION, iid).get();
-        } catch (Exception e) {
-            LOG.debug("DhcpConfig not present");
-            return null;
-        }
-        if (result.isPresent()) {
-            return result.get();
-        }
+        List<Configs> configList = Collections.singletonList(dccBuilder.build());
+        DhcpConfigBuilder dcBuilder = new DhcpConfigBuilder();
+        dcBuilder.setConfigs(configList);
+        SingleTransactionDataBroker.syncWrite(dataBroker, CONFIGURATION, iid, dcBuilder.build());
         return null;
     }
 
     private String getHelp() {
-        StringBuilder help = new StringBuilder("Usage: ");
-
-        help.append("exec dhcp-configure ");
-        help.append("[-ld/--leaseDuration leaseTime] [-dd/--defaultDomain defaultDomain]");
-        return help.toString();
+        return "Usage: \n"
+                + "exec dhcp-configure \n"
+                + "[-ld/--leaseDuration leaseTime] [-dd/--defaultDomain defaultDomain]";
     }
 
 }
index 582291841f62401b466473926730ea4e192cfd9e..8d39ea6e3a07aba0476a47d54c00cdd5ac736556 100644 (file)
@@ -8,12 +8,12 @@
 
 package org.opendaylight.netvirt.neutronvpn.shell;
 
-import com.google.common.base.Optional;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
 import org.opendaylight.netvirt.dhcpservice.api.DhcpMConstants;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.DhcpConfig;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
@@ -24,33 +24,27 @@ import org.slf4j.LoggerFactory;
 public class DhcpShowCommand extends OsgiCommandSupport {
 
     private static final Logger LOG = LoggerFactory.getLogger(DhcpShowCommand.class);
+
     private DataBroker dataBroker;
-    Integer leaseDuration = null;
-    String defDomain = null;
+    private Integer leaseDuration = null;
+    private String defDomain = null;
 
     public void setDataBroker(DataBroker broker) {
         this.dataBroker = broker;
     }
 
     @Override
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
     protected Object doExecute() throws Exception {
-        try {
-            InstanceIdentifier<DhcpConfig> iid = InstanceIdentifier.create(DhcpConfig.class);
-            DhcpConfig dhcpConfig = read(iid);
-            if (isDhcpConfigAvailable(dhcpConfig)) {
-                leaseDuration = dhcpConfig.getConfigs().get(0).getLeaseDuration();
-                defDomain = dhcpConfig.getConfigs().get(0).getDefaultDomain();
-            }
-            session.getConsole().println(
-                    "Lease Duration: " + ((leaseDuration != null) ? leaseDuration : DhcpMConstants.DEFAULT_LEASE_TIME));
-            session.getConsole().println(
-                    "Default Domain: " + ((defDomain != null) ? defDomain : DhcpMConstants.DEFAULT_DOMAIN_NAME));
-        } catch (Exception e) {
-            session.getConsole().println("Failed to fetch configuration parameters. Try again");
-            LOG.error("Failed to fetch DHCP parameters", e);
+        InstanceIdentifier<DhcpConfig> iid = InstanceIdentifier.create(DhcpConfig.class);
+        DhcpConfig dhcpConfig = SingleTransactionDataBroker.syncRead(dataBroker, CONFIGURATION, iid);
+        if (isDhcpConfigAvailable(dhcpConfig)) {
+            leaseDuration = dhcpConfig.getConfigs().get(0).getLeaseDuration();
+            defDomain = dhcpConfig.getConfigs().get(0).getDefaultDomain();
         }
+        session.getConsole().println(
+                "Lease Duration: " + (leaseDuration != null ? leaseDuration : DhcpMConstants.DEFAULT_LEASE_TIME));
+        session.getConsole().println(
+                "Default Domain: " + (defDomain != null ? defDomain : DhcpMConstants.DEFAULT_DOMAIN_NAME));
         return null;
     }
 
@@ -59,21 +53,4 @@ public class DhcpShowCommand extends OsgiCommandSupport {
                 && !dhcpConfig.getConfigs().isEmpty();
     }
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    private DhcpConfig read(InstanceIdentifier<DhcpConfig> iid) {
-
-        ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
-        Optional<DhcpConfig> result = Optional.absent();
-        try {
-            result = tx.read(LogicalDatastoreType.CONFIGURATION, iid).get();
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-        if (result.isPresent()) {
-            return result.get();
-        }
-        return null;
-    }
-
 }
index 2d7e8cc170c06906e15aa2d047aa01a63340d05d..4432082613006a6d2ae48cd03f2550a6017ea0e9 100644 (file)
@@ -14,6 +14,7 @@ import org.opendaylight.netvirt.neutronvpn.interfaces.INeutronVpnManager;
 
 @Command(scope = "vpnservice", name = "neutron-ports-show", description = "Displays neutron ports")
 public class ShowNeutronPortsCommand extends OsgiCommandSupport {
+
     private INeutronVpnManager neutronVpnManager;
 
     public void setNeutronVpnManager(INeutronVpnManager neutronVpnManager) {
index 6ffb66319b9cf2dc4ac283b0b848dae9b7304b7a..b79ca380c9c6d81c358cd4eb6f13149d67a4bfb1 100644 (file)
@@ -7,6 +7,10 @@
  */
 package org.opendaylight.netvirt.neutronvpn.shell;
 
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+import static org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker.syncReadOptional;
+
 import com.google.common.base.Optional;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -16,8 +20,7 @@ import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.commands.Option;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.SubnetOpData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.subnet.op.data.SubnetOpDataEntry;
@@ -25,7 +28,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.sub
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
-import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -34,112 +36,89 @@ import org.slf4j.LoggerFactory;
     description = "Comparison of data present in subnetMap and subnetOpDataEntry")
 public class ShowSubnet extends OsgiCommandSupport {
 
+    private static final Logger LOG = LoggerFactory.getLogger(ShowSubnet.class);
+
     @Option(name = "--subnetmap", aliases = {"--subnetmap"},
         description = "Display subnetMap details for given subnetId", required = false, multiValued = false)
     String subnetmap;
+
     @Option(name = "--subnetopdata", aliases = {"--subnetopdata"},
         description = "Display subnetOpData details for given subnetId", required = false, multiValued = false)
     String subnetopdata;
 
-    private static final Logger LOG = LoggerFactory.getLogger(ShowSubnet.class);
     private DataBroker dataBroker;
-    List<Subnetmap> subnetmapList = new ArrayList<>();
-    Map<Uuid, SubnetOpDataEntry> subnetOpDataEntryMap = new HashMap<>();
+    private List<Subnetmap> subnetmapList = new ArrayList<>();
+    private final Map<Uuid, SubnetOpDataEntry> subnetOpDataEntryMap = new HashMap<>();
 
     public void setDataBroker(DataBroker broker) {
         this.dataBroker = broker;
     }
 
     @Override
-    // TODO Clean up the console output
-    @SuppressWarnings({"checkstyle:IllegalCatch", "checkstyle:RegexpSinglelineJava"})
+    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
     protected Object doExecute() throws Exception {
-        try {
-            if ((subnetmap == null) && (subnetopdata == null)) {
-                getSubnet();
-                System.out.println("Following subnetId is present in both subnetMap and subnetOpDataEntry\n");
-                for (Subnetmap subnetmap : subnetmapList) {
-                    SubnetOpDataEntry data = subnetOpDataEntryMap.get(subnetmap.getId());
-                    if (data != null) {
-                        System.out.println(subnetmap.getId().toString() + "\n");
-                    }
+        if (subnetmap == null && subnetopdata == null) {
+            getSubnet();
+            System.out.println("Following subnetId is present in both subnetMap and subnetOpDataEntry\n");
+            for (Subnetmap subnetmap : subnetmapList) {
+                SubnetOpDataEntry data = subnetOpDataEntryMap.get(subnetmap.getId());
+                if (data != null) {
+                    System.out.println(subnetmap.getId().toString() + "\n");
                 }
-                System.out.println("\n\nFollowing subnetId is present in subnetMap but not in subnetOpDataEntry\n");
-                for (Subnetmap subnetmap : subnetmapList) {
-                    SubnetOpDataEntry data = subnetOpDataEntryMap.get(subnetmap.getId());
-                    if (data == null) {
-                        System.out.println(subnetmap.getId().toString() + "\n");
-                    }
+            }
+            System.out.println("\n\nFollowing subnetId is present in subnetMap but not in subnetOpDataEntry\n");
+            for (Subnetmap subnetmap : subnetmapList) {
+                SubnetOpDataEntry data = subnetOpDataEntryMap.get(subnetmap.getId());
+                if (data == null) {
+                    System.out.println(subnetmap.getId().toString() + "\n");
                 }
-                getshowVpnCLIHelp();
-            } else if (subnetmap == null && subnetopdata != null) {
-                InstanceIdentifier<SubnetOpDataEntry> subOpIdentifier = InstanceIdentifier.builder(SubnetOpData.class)
-                    .child(SubnetOpDataEntry.class, new SubnetOpDataEntryKey(new Uuid(subnetopdata))).build();
-                Optional<SubnetOpDataEntry> optionalSubs = read(LogicalDatastoreType.OPERATIONAL, subOpIdentifier);
-                SubnetOpDataEntry data = optionalSubs.get();
-                System.out.println("Fetching subnetmap for given subnetId\n");
-                System.out.println("------------------------------------------------------------------------------");
-                System.out.println("Key: " + data.getKey() + "\n" + "VrfId: " + data.getVrfId() + "\n" + "ElanTag: "
-                    + "" + data.getElanTag() + "\n" + "NhDpnId: " + data.getNhDpnId() + "\n" + "RouteAdvState: "
-                    + data.getRouteAdvState() + "\n" + "SubnetCidr: " + data.getSubnetCidr() + "\n"
-                    + "SubnetToDpnList: " + data.getSubnetToDpn() + "\n" + "VpnName: " + data.getVpnName() + "\n");
-                System.out.println("------------------------------------------------------------------------------");
-            } else if (subnetmap != null && subnetopdata == null) {
-                InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class)
-                        .child(Subnetmap.class, new SubnetmapKey(new Uuid(subnetmap))).build();
-                Optional<Subnetmap> sn = read(LogicalDatastoreType.CONFIGURATION, id);
-                Subnetmap data = sn.get();
-                System.out.println("Fetching subnetopdataentry for given subnetId\n");
-                System.out.println("------------------------------------------------------------------------------");
-                System.out.println("Key: " + data.getKey() + "\n" + "VpnId: " + data.getVpnId() + "\n"
-                        + "DirectPortList: " + data.getDirectPortList() + "\n" + "NetworkId: " + data.getNetworkId()
-                        + "\n" + "Network-type: " + data.getNetworkType() + "\n" + "Network-segmentation-Id: "
-                        + data.getSegmentationId() + "\n" + "PortList: " + data.getPortList() + "\n"
-                        + "RouterInterfaceFixedIp: " + data.getRouterInterfaceFixedIp() + "\n"
-                        + "RouterInterfacePortId: " + data.getRouterInterfacePortId().getValue() + "\n"
-                        + "RouterIntfMacAddress: " + data.getRouterIntfMacAddress() + "\n" + "SubnetIp: "
-                        + data.getSubnetIp() + "\n" + "TenantId: " + data.getTenantId() + "\n");
-                System.out.println("------------------------------------------------------------------------------");
             }
-        } catch (Exception e) {
-            System.out.println("Error fetching data for given subnetId ");
-            LOG.error("Error Fetching Data", e);
+            getshowVpnCLIHelp();
+        } else if (subnetmap == null && subnetopdata != null) {
+            InstanceIdentifier<SubnetOpDataEntry> subOpIdentifier = InstanceIdentifier.builder(SubnetOpData.class)
+                .child(SubnetOpDataEntry.class, new SubnetOpDataEntryKey(new Uuid(subnetopdata))).build();
+            Optional<SubnetOpDataEntry> optionalSubs = syncReadOptional(dataBroker, OPERATIONAL, subOpIdentifier);
+            SubnetOpDataEntry data = optionalSubs.get();
+            System.out.println("Fetching subnetmap for given subnetId\n");
+            System.out.println("------------------------------------------------------------------------------");
+            System.out.println("Key: " + data.getKey() + "\n" + "VrfId: " + data.getVrfId() + "\n" + "ElanTag: "
+                + "" + data.getElanTag() + "\n" + "NhDpnId: " + data.getNhDpnId() + "\n" + "RouteAdvState: "
+                + data.getRouteAdvState() + "\n" + "SubnetCidr: " + data.getSubnetCidr() + "\n"
+                + "SubnetToDpnList: " + data.getSubnetToDpn() + "\n" + "VpnName: " + data.getVpnName() + "\n");
+            System.out.println("------------------------------------------------------------------------------");
+        } else if (subnetmap != null && subnetopdata == null) {
+            InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class)
+                    .child(Subnetmap.class, new SubnetmapKey(new Uuid(subnetmap))).build();
+            Optional<Subnetmap> sn = syncReadOptional(dataBroker, CONFIGURATION, id);
+            Subnetmap data = sn.get();
+            System.out.println("Fetching subnetopdataentry for given subnetId\n");
+            System.out.println("------------------------------------------------------------------------------");
+            System.out.println("Key: " + data.getKey() + "\n" + "VpnId: " + data.getVpnId() + "\n"
+                    + "DirectPortList: " + data.getDirectPortList() + "\n" + "NetworkId: " + data.getNetworkId()
+                    + "\n" + "Network-type: " + data.getNetworkType() + "\n" + "Network-segmentation-Id: "
+                    + data.getSegmentationId() + "\n" + "PortList: " + data.getPortList() + "\n"
+                    + "RouterInterfaceFixedIp: " + data.getRouterInterfaceFixedIp() + "\n"
+                    + "RouterInterfacePortId: " + data.getRouterInterfacePortId().getValue() + "\n"
+                    + "RouterIntfMacAddress: " + data.getRouterIntfMacAddress() + "\n" + "SubnetIp: "
+                    + data.getSubnetIp() + "\n" + "TenantId: " + data.getTenantId() + "\n");
+            System.out.println("------------------------------------------------------------------------------");
         }
-
         return null;
     }
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
-                                                    InstanceIdentifier<T> path) {
-
-        ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
-
-        Optional<T> result = Optional.absent();
-        try {
-            result = tx.read(datastoreType, path).get();
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-
-        return result;
-    }
-
-    // TODO Clean up the console output
     @SuppressWarnings("checkstyle:RegexpSinglelineJava")
-    private void getSubnet() {
+    private void getSubnet() throws ReadFailedException {
         List<SubnetOpDataEntry> subnetOpDataEntryList = new ArrayList<>();
         InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
         InstanceIdentifier<SubnetOpData> subOpIdentifier = InstanceIdentifier.builder(SubnetOpData.class).build();
-        Optional<Subnetmaps> optionalSubnetmaps = read(LogicalDatastoreType.CONFIGURATION, subnetmapsid);
+        Optional<Subnetmaps> optionalSubnetmaps = syncReadOptional(dataBroker, CONFIGURATION, subnetmapsid);
         if (!optionalSubnetmaps.isPresent()) {
             System.out.println("No Subnetmaps configured.");
         } else {
             subnetmapList = optionalSubnetmaps.get().getSubnetmap();
         }
 
-        Optional<SubnetOpData> optionalSubnetOpData = read(LogicalDatastoreType.OPERATIONAL, subOpIdentifier);
+        Optional<SubnetOpData> optionalSubnetOpData = syncReadOptional(dataBroker, OPERATIONAL, subOpIdentifier);
         if (!optionalSubnetOpData.isPresent()) {
             System.out.println("No SubnetOpData configured.");
         } else {
index 9f41b8a0d1a0afcdf8456308424b3ebe1ed73e44..a038d47dc09403be07e9347df9ef9cd73a62c8c8 100644 (file)
@@ -28,7 +28,6 @@ public class ShowVpnConfigCommand extends OsgiCommandSupport {
 
     @Override
     protected Object doExecute() throws Exception {
-
         Uuid vuuid = null;
         if (vid != null) {
             vuuid = new Uuid(vid);
index f9a421b643119e3a1630b1c49c09b58339621e55..c0f6b0b95d316442b1c291be8b6d3f844d6a8fca 100644 (file)
@@ -7,6 +7,10 @@
  */
 package org.opendaylight.netvirt.neutronvpn.shell;
 
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+import static org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker.syncReadOptional;
+
 import com.google.common.base.Optional;
 import java.util.ArrayList;
 import java.util.List;
@@ -14,15 +18,13 @@ import org.apache.karaf.shell.commands.Argument;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.LearntVpnVipToPortData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPort;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.learnt.vpn.vip.to.port.data.LearntVpnVipToPortKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NeutronVpnPortipPortData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPort;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.vpn.portip.port.data.VpnPortipToPortKey;
-import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -32,6 +34,8 @@ import org.slf4j.LoggerFactory;
         + "VPN Instance(s)")
 public class ShowVpnIpToPort extends OsgiCommandSupport {
 
+    private static final Logger LOG = LoggerFactory.getLogger(ShowVpnIpToPort.class);
+
     @Argument(index = 0, name = "--vpn-name", description = "Name of the Vpn Instance", required = false,
         multiValued = false)
     private String vpnName;
@@ -39,107 +43,83 @@ public class ShowVpnIpToPort extends OsgiCommandSupport {
         required = false, multiValued = false)
     private String portFixedIp;
 
-    private static final Logger LOG = LoggerFactory.getLogger(ShowVpnIpToPort.class);
     private DataBroker dataBroker;
-    List<VpnPortipToPort> vpnPortipToPortList = new ArrayList<>();
-    List<LearntVpnVipToPort> vpnVipToPortList = new ArrayList<>();
+    private List<VpnPortipToPort> vpnPortipToPortList = new ArrayList<>();
+    private List<LearntVpnVipToPort> vpnVipToPortList = new ArrayList<>();
 
     public void setDataBroker(DataBroker broker) {
         this.dataBroker = broker;
     }
 
     @Override
-    // TODO Clean up the exception handling and the console output
-    @SuppressWarnings({"checkstyle:IllegalCatch", "checkstyle:RegexpSinglelineJava"})
+    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
     protected Object doExecute() throws Exception {
-        try {
-            if (vpnName == null && portFixedIp == null) {
-                getNeutronVpnPort();
-                getLearntVpnVipPort();
-                System.out.println(vpnPortipToPortList.size() + " Entries are present: ");
-                System.out.println("-----------------------------------------------------------------------");
-                System.out.println(String.format("             %s   %24s   %20s   %32s", "VpnName", "IPAddress",
-                    "MacAddress", "Port"));
-                System.out.println("-----------------------------------------------------------------------");
-                for (VpnPortipToPort vpnPortipToPort : vpnPortipToPortList) {
-                    System.out.println(String.format("  %-32s  %-16s  %-16s  %-32s", vpnPortipToPort.getVpnName(),
-                            vpnPortipToPort.getPortFixedip(),
-                            vpnPortipToPort.getMacAddress(),
-                            vpnPortipToPort.getPortName()));
-                }
-                for (LearntVpnVipToPort learntVpnVipToPort : vpnVipToPortList) {
-                    System.out.println(String.format("* %-32s  %-16s  %-16s  %-32s", learntVpnVipToPort.getVpnName(),
-                            learntVpnVipToPort.getPortFixedip(),
-                            learntVpnVipToPort.getMacAddress(),
-                            learntVpnVipToPort.getPortName()));
-                }
-                System.out.println("\n * prefixed entries are Learned.");
-                System.out.println("\n" + getshowVpnCLIHelp());
-            } else if (portFixedIp == null || vpnName == null) {
-                System.out.println("Insufficient arguments"
-                    + "\nCorrect Usage : neutronvpn-port-show [<vpnName> <portFixedIp>]");
+        if (vpnName == null && portFixedIp == null) {
+            getNeutronVpnPort();
+            getLearntVpnVipPort();
+            System.out.println(vpnPortipToPortList.size() + " Entries are present: ");
+            System.out.println("-----------------------------------------------------------------------");
+            System.out.println(String.format("             %s   %24s   %20s   %32s", "VpnName", "IPAddress",
+                "MacAddress", "Port"));
+            System.out.println("-----------------------------------------------------------------------");
+            for (VpnPortipToPort vpnPortipToPort : vpnPortipToPortList) {
+                System.out.println(String.format("  %-32s  %-16s  %-16s  %-32s", vpnPortipToPort.getVpnName(),
+                        vpnPortipToPort.getPortFixedip(),
+                        vpnPortipToPort.getMacAddress(),
+                        vpnPortipToPort.getPortName()));
+            }
+            for (LearntVpnVipToPort learntVpnVipToPort : vpnVipToPortList) {
+                System.out.println(String.format("* %-32s  %-16s  %-16s  %-32s", learntVpnVipToPort.getVpnName(),
+                        learntVpnVipToPort.getPortFixedip(),
+                        learntVpnVipToPort.getMacAddress(),
+                        learntVpnVipToPort.getPortName()));
+            }
+            System.out.println("\n * prefixed entries are Learned.");
+            System.out.println("\n" + getshowVpnCLIHelp());
+        } else if (portFixedIp == null || vpnName == null) {
+            System.out.println("Insufficient arguments"
+                + "\nCorrect Usage : neutronvpn-port-show [<vpnName> <portFixedIp>]");
+        } else {
+            InstanceIdentifier<VpnPortipToPort> id =
+                InstanceIdentifier.builder(NeutronVpnPortipPortData.class)
+                    .child(VpnPortipToPort.class, new VpnPortipToPortKey(portFixedIp, vpnName)).build();
+            Optional<VpnPortipToPort> vpnPortipToPortData = syncReadOptional(dataBroker, CONFIGURATION, id);
+            if (vpnPortipToPortData.isPresent()) {
+                VpnPortipToPort data = vpnPortipToPortData.get();
+                System.out.println("\n----------"
+                    + "---------------------------------------------------------------------------------");
+                System.out.println("VpnName:   " + data.getVpnName() + "\nIPAddress: " + data.getPortFixedip()
+                    + "\nMacAddress: " + data.getMacAddress() + "\nPort: " + data.getPortName());
+                System.out.println("\n----------"
+                    + "---------------------------------------------------------------------------------");
             } else {
-                InstanceIdentifier<VpnPortipToPort> id =
-                    InstanceIdentifier.builder(NeutronVpnPortipPortData.class)
-                        .child(VpnPortipToPort.class, new VpnPortipToPortKey(portFixedIp, vpnName)).build();
-                Optional<VpnPortipToPort> vpnPortipToPortData = read(LogicalDatastoreType.CONFIGURATION, id);
-                if (vpnPortipToPortData.isPresent()) {
-                    VpnPortipToPort data = vpnPortipToPortData.get();
-                    System.out.println("\n----------"
-                        + "---------------------------------------------------------------------------------");
-                    System.out.println("VpnName:   " + data.getVpnName() + "\nIPAddress: " + data.getPortFixedip()
-                        + "\nMacAddress: " + data.getMacAddress() + "\nPort: " + data.getPortName());
-                    System.out.println("\n----------"
-                        + "---------------------------------------------------------------------------------");
-                } else {
-                    InstanceIdentifier<LearntVpnVipToPort> learntId =
-                        InstanceIdentifier.builder(LearntVpnVipToPortData.class)
-                            .child(LearntVpnVipToPort.class, new LearntVpnVipToPortKey(portFixedIp, vpnName)).build();
-                    Optional<LearntVpnVipToPort> learntVpnVipToPortData =
-                        read(LogicalDatastoreType.OPERATIONAL, learntId);
-                    if (!learntVpnVipToPortData.isPresent()) {
-                        System.out.println("Data not available");
-                        return null;
-                    }
-                    LearntVpnVipToPort data = learntVpnVipToPortData.get();
-                    System.out.println("\n----------"
-                        + "---------------------------------------------------------------------------------");
-                    System.out.println("VpnName: * " + data.getVpnName() + "\nIPAddress: " + data.getPortFixedip()
-                        + "\nMacAddress: " + data.getMacAddress() + "\nPort: " + data.getPortName());
-                    System.out.println("\n----------"
-                        + "---------------------------------------------------------------------------------");
+                InstanceIdentifier<LearntVpnVipToPort> learntId =
+                    InstanceIdentifier.builder(LearntVpnVipToPortData.class)
+                        .child(LearntVpnVipToPort.class, new LearntVpnVipToPortKey(portFixedIp, vpnName)).build();
+                Optional<LearntVpnVipToPort> learntVpnVipToPortData =
+                        syncReadOptional(dataBroker, OPERATIONAL, learntId);
+                if (!learntVpnVipToPortData.isPresent()) {
+                    System.out.println("Data not available");
+                    return null;
                 }
-                System.out.println("\n" + getshowVpnCLIHelp());
+                LearntVpnVipToPort data = learntVpnVipToPortData.get();
+                System.out.println("\n----------"
+                    + "---------------------------------------------------------------------------------");
+                System.out.println("VpnName: * " + data.getVpnName() + "\nIPAddress: " + data.getPortFixedip()
+                    + "\nMacAddress: " + data.getMacAddress() + "\nPort: " + data.getPortName());
+                System.out.println("\n----------"
+                    + "---------------------------------------------------------------------------------");
             }
-        } catch (Exception e) {
-            System.out.println("Error fetching vpnToPortData for [vpnName=" + vpnName + ", portFixedip="
-                + portFixedIp + "]");
-            LOG.error("Error Fetching Data ", e);
+            System.out.println("\n" + getshowVpnCLIHelp());
         }
-
         return null;
     }
 
-    // TODO Clean up the exception handling
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
-                                                    InstanceIdentifier<T> path) {
-        ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
-        Optional<T> result = Optional.absent();
-        try {
-            result = tx.read(datastoreType, path).get();
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-        return result;
-    }
-
-    // TODO Clean up the console output
     @SuppressWarnings("checkstyle:RegexpSinglelineJava")
-    private void getNeutronVpnPort() {
+    private void getNeutronVpnPort() throws ReadFailedException {
         InstanceIdentifier<NeutronVpnPortipPortData> neutronVpnPortipPortDataIdentifier = InstanceIdentifier
                 .builder(NeutronVpnPortipPortData.class).build();
-        Optional<NeutronVpnPortipPortData> optionalNeutronVpnPort = read(LogicalDatastoreType.CONFIGURATION,
+        Optional<NeutronVpnPortipPortData> optionalNeutronVpnPort = syncReadOptional(dataBroker, CONFIGURATION,
                 neutronVpnPortipPortDataIdentifier);
         if (!optionalNeutronVpnPort.isPresent()) {
             System.out.println("No NeutronVpnPortIpToPortData configured.");
@@ -148,12 +128,11 @@ public class ShowVpnIpToPort extends OsgiCommandSupport {
         }
     }
 
-    // TODO Clean up the console output
     @SuppressWarnings("checkstyle:RegexpSinglelineJava")
-    private void getLearntVpnVipPort() {
+    private void getLearntVpnVipPort() throws ReadFailedException {
         InstanceIdentifier<LearntVpnVipToPortData> learntVpnVipPortDataIdentifier = InstanceIdentifier
                 .builder(LearntVpnVipToPortData.class).build();
-        Optional<LearntVpnVipToPortData> optionalLearntVpnPort = read(LogicalDatastoreType.OPERATIONAL,
+        Optional<LearntVpnVipToPortData> optionalLearntVpnPort = syncReadOptional(dataBroker, OPERATIONAL,
                 learntVpnVipPortDataIdentifier);
         if (!optionalLearntVpnPort.isPresent()) {
             System.out.println("No LearntVpnVipToPortData discovered.");