Convert users of Optional.get() 27/105627/1
authorRobert Varga <robert.varga@pantheon.tech>
Sat, 22 Apr 2023 17:42:01 +0000 (19:42 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Sun, 23 Apr 2023 15:57:24 +0000 (17:57 +0200)
Upgraded modernized plugin is flagging callers of Optional.get(). This
is a good opportunity to inspect how exactly we use Optionals.

It turns out we can improve things significantly by taking advantage of
improved interfaces in yang.data.api: using childByArg()/getChildByArg()
we can:
- remove explicit calls to verifyNotNull()
- remove duplicate lookups of nodes
- remove Optional.ifPresent() indirection

Change-Id: If1f898f3e12e730e8084cca9689f94949c53c852
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
(cherry picked from commit fe8217050d67666bb2ffd8d6ee3bdcfd52867d6d)

49 files changed:
bgp/extensions/evpn/src/main/java/org/opendaylight/protocol/bgp/evpn/impl/esi/types/EsiModelUtil.java
bgp/extensions/evpn/src/main/java/org/opendaylight/protocol/bgp/evpn/impl/nlri/AbstractEvpnNlri.java
bgp/extensions/evpn/src/main/java/org/opendaylight/protocol/bgp/evpn/impl/nlri/EvpnNlriParser.java
bgp/extensions/evpn/src/main/java/org/opendaylight/protocol/bgp/evpn/impl/nlri/NlriModelUtil.java
bgp/extensions/flowspec/src/main/java/org/opendaylight/protocol/bgp/flowspec/AbstractFlowspecNlriParser.java
bgp/extensions/flowspec/src/main/java/org/opendaylight/protocol/bgp/flowspec/AbstractFlowspecRIBSupport.java
bgp/extensions/flowspec/src/main/java/org/opendaylight/protocol/bgp/flowspec/ipv4/FlowspecIpv4NlriParserHelper.java
bgp/extensions/flowspec/src/main/java/org/opendaylight/protocol/bgp/flowspec/ipv6/FlowspecIpv6NlriParserHelper.java
bgp/extensions/inet/src/main/java/org/opendaylight/protocol/bgp/inet/IPv4RIBSupport.java
bgp/extensions/inet/src/main/java/org/opendaylight/protocol/bgp/inet/IPv6RIBSupport.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/LinkstateRIBSupport.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/nlri/LinkNlriParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/nlri/LinkstateNlriParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/nlri/NodeNlriParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/tlvs/MultiTopoIdTlvParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/tlvs/OspfRouteTlvParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/impl/tlvs/ReachTlvParser.java
bgp/extensions/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/spi/AbstractTeLspNlriCodec.java
bgp/extensions/route-target/src/main/java/org/opendaylight/protocol/bgp/route/targetcontrain/impl/route/policy/ClientAttributePrependHandler.java
bgp/openconfig-rp-impl/src/main/java/org/opendaylight/protocol/bgp/openconfig/routing/policy/impl/BGPRibPolicyImpl.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/BGPOpenMessageParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/BGPUpdateMessageParser.java
bgp/parser-spi/src/main/java/org/opendaylight/protocol/bgp/parser/spi/MultiPathSupportUtil.java
bgp/parser-spi/src/main/java/org/opendaylight/protocol/bgp/parser/spi/PathIdUtil.java
bgp/path-selection-mode/src/main/java/org/opendaylight/protocol/bgp/mode/impl/BestPathStateImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AbstractPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibInWriter.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibOutListener.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/ApplicationPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/LocRibWriter.java
bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/AbstractRIBSupport.java
bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/IdentifierUtils.java
bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/app/BmpRouterImpl.java
pcep/api/src/main/java/org/opendaylight/protocol/pcep/TerminationReason.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/Main.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/PCCTunnelManagerImpl.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/PCCsBuilder.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/spi/MsgBuilderUtil.java
pcep/spi/src/main/java/org/opendaylight/protocol/pcep/spi/AbstractObjectWithTlvsParser.java
pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/PCEPTopologySessionListener.java
pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/TopologyNodeState.java
pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/TopologyStatsRpcServiceImpl.java
pcep/tunnel/tunnel-provider/src/main/java/org/opendaylight/bgpcep/pcep/tunnel/provider/CreateTunnelInstructionExecutor.java
pcep/tunnel/tunnel-provider/src/main/java/org/opendaylight/bgpcep/pcep/tunnel/provider/DestroyTunnelInstructionExecutor.java
pcep/tunnel/tunnel-provider/src/main/java/org/opendaylight/bgpcep/pcep/tunnel/provider/NodeChangedListener.java
pcep/tunnel/tunnel-provider/src/main/java/org/opendaylight/bgpcep/pcep/tunnel/provider/UpdateTunnelInstructionExecutor.java
testtool-util/src/main/java/org/opendaylight/protocol/util/CheckTestUtil.java

index 6214d6dc11899a3cd1d8bb534b6a0327cac5d056..e985b56dd78d52a77c2e048e19cb2d4da1c888a8 100644 (file)
@@ -47,11 +47,11 @@ final class EsiModelUtil {
     }
 
     static Uint32 extractLD(final ContainerNode cont) {
-        return (Uint32) cont.findChildByArg(LD_NID).get().body();
+        return (Uint32) cont.getChildByArg(LD_NID).body();
     }
 
     static Arbitrary extractArbitrary(final ContainerNode esi) {
-        final byte[] arbitrary = (byte[]) esi.findChildByArg(ARB_NID).get().body();
+        final byte[] arbitrary = (byte[]) esi.getChildByArg(ARB_NID).body();
         checkArgument(arbitrary.length == ArbitraryParser.ARBITRARY_LENGTH,
                 "Wrong length of array of bytes. Expected: %s Passed: %s "
                         + ";", ArbitraryParser.ARBITRARY_LENGTH, arbitrary.length);
@@ -59,34 +59,34 @@ final class EsiModelUtil {
     }
 
     static AsNumber extractAS(final ContainerNode asGen) {
-        return new AsNumber((Uint32) asGen.findChildByArg(AS_NID).get().body());
+        return new AsNumber((Uint32) asGen.getChildByArg(AS_NID).body());
     }
 
     static Uint16 extractPK(final ContainerNode t1) {
-        return (Uint16) t1.findChildByArg(PK_NID).get().body();
+        return (Uint16) t1.getChildByArg(PK_NID).body();
     }
 
     static MacAddress extractLacpMac(final ContainerNode t1) {
-        return new MacAddress((String) t1.findChildByArg(LACP_MAC_NID).get().body());
+        return new MacAddress((String) t1.getChildByArg(LACP_MAC_NID).body());
     }
 
     static MacAddress extractBrigeMac(final ContainerNode lan) {
-        return new MacAddress((String) lan.findChildByArg(BRIDGE_MAC_NID).get().body());
+        return new MacAddress((String) lan.getChildByArg(BRIDGE_MAC_NID).body());
     }
 
     static Uint16 extractBP(final ContainerNode lan) {
-        return (Uint16) lan.findChildByArg(RBP_NID).get().body();
+        return (Uint16) lan.getChildByArg(RBP_NID).body();
     }
 
     static Uint24 extractUint24LD(final ContainerNode esiVal) {
-        return new Uint24((Uint32) esiVal.findChildByArg(LD_NID).get().body());
+        return new Uint24((Uint32) esiVal.getChildByArg(LD_NID).body());
     }
 
     static MacAddress extractSystmeMac(final ContainerNode macGEn) {
-        return new MacAddress((String) macGEn.findChildByArg(SYSTEM_MAC_NID).get().body());
+        return new MacAddress((String) macGEn.getChildByArg(SYSTEM_MAC_NID).body());
     }
 
     static Ipv4AddressNoZone extractRD(final ContainerNode t4) {
-        return new Ipv4AddressNoZone((String) t4.findChildByArg(RD_NID).get().body());
+        return new Ipv4AddressNoZone((String) t4.getChildByArg(RD_NID).body());
     }
 }
index da342273daec5f330bdd38b3e8dd75d1092001f0..9288d53ae6019945fbf3bd070d2e0046c273b60e 100644 (file)
@@ -7,8 +7,6 @@
  */
 package org.opendaylight.protocol.bgp.evpn.impl.nlri;
 
-import static com.google.common.base.Verify.verifyNotNull;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import org.opendaylight.protocol.bgp.evpn.impl.esi.types.SimpleEsiTypeRegistry;
@@ -43,6 +41,6 @@ abstract class AbstractEvpnNlri implements EvpnParser, EvpnSerializer {
     protected abstract ByteBuf serializeBody(EvpnChoice evpn);
 
     protected static Esi serializeEsi(final ContainerNode evpn) {
-        return SimpleEsiTypeRegistry.getInstance().parseEsiModel((ChoiceNode) verifyNotNull(evpn.childByArg(ESI_NID)));
+        return SimpleEsiTypeRegistry.getInstance().parseEsiModel((ChoiceNode) evpn.getChildByArg(ESI_NID));
     }
 }
index 151a32caed0892d19ff26bfda261985f77ff5e4d..7b027f9e72bf4c2a3540ba8631b9c0145cae4a83 100644 (file)
@@ -69,7 +69,7 @@ public final class EvpnNlriParser implements NlriParser, NlriSerializer {
     private static EvpnDestination extractDestination(final DataContainerNode route,
             final ExtractionInterface extract) {
         final EvpnRegistry reg = SimpleEvpnNlriRegistry.getInstance();
-        final ChoiceNode cont = (ChoiceNode) route.findChildByArg(EVPN_CHOICE_NID).get();
+        final ChoiceNode cont = (ChoiceNode) route.getChildByArg(EVPN_CHOICE_NID);
         final EvpnChoice evpnValue = extract.check(reg, cont);
         if (evpnValue == null) {
             LOG.warn("Unrecognized Nlri {}", cont);
index 0c8f0dbfc7b61b1a7e014ac9352e63d2a90d6e7a..9f4596eb6a6fd88e9e10d6e00379a8a3258d0ca6 100644 (file)
@@ -52,30 +52,30 @@ final class NlriModelUtil {
     }
 
     static RouteDistinguisher extractRouteDistinguisher(final DataContainerNode evpn) {
-        return RouteDistinguisherBuilder.getDefaultInstance((String) evpn.findChildByArg(RD_NID).get().body());
+        return RouteDistinguisherBuilder.getDefaultInstance((String) evpn.getChildByArg(RD_NID).body());
     }
 
     static IpAddressNoZone extractOrigRouteIp(final DataContainerNode evpn) {
-        return parseIpAddress((String) evpn.findChildByArg(ORI_NID).get().body());
+        return parseIpAddress((String) evpn.getChildByArg(ORI_NID).body());
     }
 
     static EthernetTagId extractETI(final ContainerNode evpn) {
-        final ContainerNode eti = (ContainerNode) evpn.findChildByArg(ETI_NID).get();
-        return new EthernetTagIdBuilder().setVlanId((Uint32) eti.findChildByArg(VLAN_NID).get().body()).build();
+        final ContainerNode eti = (ContainerNode) evpn.getChildByArg(ETI_NID);
+        return new EthernetTagIdBuilder().setVlanId((Uint32) eti.getChildByArg(VLAN_NID).body()).build();
     }
 
     static MacAddress extractMAC(final DataContainerNode evpn) {
-        return new MacAddress((String) evpn.findChildByArg(MAC_NID).get().body());
+        return new MacAddress((String) evpn.getChildByArg(MAC_NID).body());
     }
 
     static IpAddressNoZone extractIp(final DataContainerNode evpn) {
-        return evpn.findChildByArg(IP_NID)
-            .map(child -> parseIpAddress((String) child.body()))
-            .orElse(null);
+        final var ip = evpn.childByArg(IP_NID);
+        return ip == null ? null : parseIpAddress((String) ip.body());
     }
 
     static MplsLabel extractMplsLabel(final DataContainerNode evpn, final NodeIdentifier mplsNid) {
-        return evpn.findChildByArg(mplsNid).map(child -> new MplsLabel((Uint32) child.body())).orElse(null);
+        final var label = evpn.childByArg(mplsNid);
+        return label == null ? null : new MplsLabel((Uint32) label.body());
     }
 
     private static IpAddressNoZone parseIpAddress(final String str) {
index 4d9541f7fa61d4f1430579915a8d854b89031589..00f4932950735299b67d0e4334e8a3b0c11426c6 100644 (file)
@@ -16,7 +16,6 @@ import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 import org.eclipse.jdt.annotation.NonNull;
@@ -256,14 +255,13 @@ public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSeri
     public final List<Flowspec> extractFlowspec(final DataContainerNode route) {
         requireNonNull(route, "Cannot extract flowspec from null route.d");
         final List<Flowspec> fsList = new ArrayList<>();
-        final Optional<DataContainerChild> flowspecs = route.findChildByArg(FLOWSPEC_NID);
-        if (flowspecs.isPresent()) {
-            for (final UnkeyedListEntryNode flowspec : ((UnkeyedListNode) flowspecs.get()).body()) {
+        final DataContainerChild flowspecs = route.childByArg(FLOWSPEC_NID);
+        if (flowspecs != null) {
+            for (final UnkeyedListEntryNode flowspec : ((UnkeyedListNode) flowspecs).body()) {
                 final FlowspecBuilder fsBuilder = new FlowspecBuilder();
-                final Optional<DataContainerChild> flowspecType = flowspec.findChildByArg(FLOWSPEC_TYPE_NID);
-                if (flowspecType.isPresent()) {
-                    final ChoiceNode fsType = (ChoiceNode) flowspecType.get();
-                    processFlowspecType(fsType, fsBuilder);
+                final DataContainerChild flowspecType = flowspec.childByArg(FLOWSPEC_TYPE_NID);
+                if (flowspecType != null) {
+                    processFlowspecType((ChoiceNode) flowspecType, fsBuilder);
                 }
                 fsList.add(fsBuilder.build());
             }
@@ -272,179 +270,209 @@ public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSeri
     }
 
     private void processFlowspecType(final ChoiceNode fsType, final FlowspecBuilder fsBuilder) {
-        if (fsType.findChildByArg(PORTS_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new PortCaseBuilder()
-                    .setPorts(createPorts((UnkeyedListNode) fsType.findChildByArg(PORTS_NID).get())).build());
-        } else if (fsType.findChildByArg(DEST_PORT_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new DestinationPortCaseBuilder()
-                    .setDestinationPorts(createDestinationPorts(
-                        (UnkeyedListNode) fsType.findChildByArg(DEST_PORT_NID).get()))
-                    .build());
-        } else if (fsType.findChildByArg(SOURCE_PORT_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new SourcePortCaseBuilder()
-                    .setSourcePorts(createSourcePorts((UnkeyedListNode) fsType.findChildByArg(SOURCE_PORT_NID).get()))
-                    .build());
-        } else if (fsType.findChildByArg(ICMP_TYPE_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new IcmpTypeCaseBuilder()
-                    .setTypes(createTypes((UnkeyedListNode) fsType.findChildByArg(ICMP_TYPE_NID).get())).build());
-        } else if (fsType.findChildByArg(ICMP_CODE_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new IcmpCodeCaseBuilder()
-                    .setCodes(createCodes((UnkeyedListNode) fsType.findChildByArg(ICMP_CODE_NID).get())).build());
-        } else if (fsType.findChildByArg(TCP_FLAGS_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new TcpFlagsCaseBuilder()
-                    .setTcpFlags(createTcpFlags((UnkeyedListNode) fsType.findChildByArg(TCP_FLAGS_NID).get())).build());
-        } else if (fsType.findChildByArg(PACKET_LENGTHS_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new PacketLengthCaseBuilder()
-                    .setPacketLengths(createPacketLengths(
-                        (UnkeyedListNode) fsType.findChildByArg(PACKET_LENGTHS_NID).get()))
-                    .build());
-        } else if (fsType.findChildByArg(DSCP_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new DscpCaseBuilder()
-                    .setDscps(createDscpsLengths((UnkeyedListNode) fsType.findChildByArg(DSCP_NID).get())).build());
-        } else if (fsType.findChildByArg(FRAGMENT_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new FragmentCaseBuilder()
-                    .setFragments(createFragments(
-                        (UnkeyedListNode) fsType.findChildByArg(FRAGMENT_NID).get())).build());
+        final var common = processCommonFlowspec(fsType);
+        if (common != null) {
+            fsBuilder.setFlowspecType(common);
         } else {
             extractSpecificFlowspec(fsType, fsBuilder);
         }
     }
 
-    private static List<Ports> createPorts(final UnkeyedListNode portsData) {
-        final List<Ports> ports = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : portsData.body()) {
-            final PortsBuilder portsBuilder = new PortsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(
-                dataContainerChild -> portsBuilder.setOp(NumericTwoByteOperandParser.INSTANCE.create(
-                    (Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> portsBuilder.setValue((Uint16) dataContainerChild.body()));
-            ports.add(portsBuilder.build());
+    private static @Nullable FlowspecType processCommonFlowspec(final ChoiceNode fsType) {
+        final var ports = fsType.childByArg(PORTS_NID);
+        if (ports != null) {
+            return new PortCaseBuilder().setPorts(createPorts((UnkeyedListNode) ports)).build();
+        }
+        final var destPort = fsType.childByArg(DEST_PORT_NID);
+        if (destPort != null) {
+            return new DestinationPortCaseBuilder()
+                .setDestinationPorts(createDestinationPorts((UnkeyedListNode) destPort))
+                .build();
+        }
+        final var sourcePort = fsType.childByArg(SOURCE_PORT_NID);
+        if (sourcePort != null) {
+            return new SourcePortCaseBuilder().setSourcePorts(createSourcePorts((UnkeyedListNode) sourcePort)).build();
+        }
+        final var icmpType = fsType.childByArg(ICMP_TYPE_NID);
+        if (icmpType != null) {
+            return new IcmpTypeCaseBuilder().setTypes(createTypes((UnkeyedListNode) icmpType)).build();
+        }
+        final var icmpCode = fsType.childByArg(ICMP_CODE_NID);
+        if (icmpCode != null) {
+            return new IcmpCodeCaseBuilder().setCodes(createCodes((UnkeyedListNode) icmpCode)).build();
+        }
+        final var tcpFlags = fsType.childByArg(TCP_FLAGS_NID);
+        if (tcpFlags != null) {
+            return new TcpFlagsCaseBuilder().setTcpFlags(createTcpFlags((UnkeyedListNode) tcpFlags)).build();
         }
+        final var packetLengths = fsType.childByArg(PACKET_LENGTHS_NID);
+        if (packetLengths != null) {
+            return new PacketLengthCaseBuilder()
+                .setPacketLengths(createPacketLengths((UnkeyedListNode) packetLengths))
+                .build();
+        }
+        final var dscp = fsType.childByArg(DSCP_NID);
+        if (dscp != null) {
+            return new DscpCaseBuilder().setDscps(createDscpsLengths((UnkeyedListNode) dscp)).build();
+        }
+        final var fragment = fsType.childByArg(FRAGMENT_NID);
+        if (fragment != null) {
+            return new FragmentCaseBuilder().setFragments(createFragments((UnkeyedListNode) fragment)).build();
+        }
+        return null;
+    }
 
-        return ports;
+    private static List<Ports> createPorts(final UnkeyedListNode portsData) {
+        return portsData.body().stream()
+            .map(node -> {
+                final var builder = new PortsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericTwoByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint16) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<DestinationPorts> createDestinationPorts(final UnkeyedListNode destinationPortsData) {
-        final List<DestinationPorts> destinationPorts = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : destinationPortsData.body()) {
-            final DestinationPortsBuilder destPortsBuilder = new DestinationPortsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> destPortsBuilder.setOp(
-                NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> destPortsBuilder.setValue((Uint16) dataContainerChild.body()));
-            destinationPorts.add(destPortsBuilder.build());
-        }
-
-        return destinationPorts;
+        return destinationPortsData.body().stream()
+            .map(node -> {
+                final var builder = new DestinationPortsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericTwoByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint16) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<SourcePorts> createSourcePorts(final UnkeyedListNode sourcePortsData) {
-        final List<SourcePorts> sourcePorts = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : sourcePortsData.body()) {
-            final SourcePortsBuilder sourcePortsBuilder = new SourcePortsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> sourcePortsBuilder.setOp(
-                NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> sourcePortsBuilder.setValue((Uint16) dataContainerChild.body()));
-            sourcePorts.add(sourcePortsBuilder.build());
-        }
-
-        return sourcePorts;
+        return sourcePortsData.body().stream()
+            .map(node -> {
+                final var builder = new SourcePortsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericTwoByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint16) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<Types> createTypes(final UnkeyedListNode typesData) {
-        final List<Types> types = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : typesData.body()) {
-            final TypesBuilder typesBuilder = new TypesBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> typesBuilder.setOp(
-                NumericOneByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> typesBuilder.setValue((Uint8) dataContainerChild.body()));
-            types.add(typesBuilder.build());
-        }
-
-        return types;
+        return typesData.body().stream()
+            .map(node -> {
+                final var builder = new TypesBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint8) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<Codes> createCodes(final UnkeyedListNode codesData) {
-        final List<Codes> codes = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : codesData.body()) {
-            final CodesBuilder codesBuilder = new CodesBuilder();
-            node.findChildByArg(OP_NID).ifPresent(
-                dataContainerChild -> codesBuilder.setOp(NumericOneByteOperandParser
-                    .INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> codesBuilder.setValue((Uint8) dataContainerChild.body()));
-            codes.add(codesBuilder.build());
-        }
-
-        return codes;
+        return codesData.body().stream()
+            .map(node -> {
+                final var builder = new CodesBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint8) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<TcpFlags> createTcpFlags(final UnkeyedListNode tcpFlagsData) {
-        final List<TcpFlags> tcpFlags = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : tcpFlagsData.body()) {
-            final TcpFlagsBuilder tcpFlagsBuilder = new TcpFlagsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> tcpFlagsBuilder
-                    .setOp(BitmaskOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> tcpFlagsBuilder.setValue((Uint16) dataContainerChild.body()));
-            tcpFlags.add(tcpFlagsBuilder.build());
-        }
-
-        return tcpFlags;
+        return tcpFlagsData.body().stream()
+            .map(node -> {
+                final var builder = new TcpFlagsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(BitmaskOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint16) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<PacketLengths> createPacketLengths(final UnkeyedListNode packetLengthsData) {
-        final List<PacketLengths> packetLengths = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : packetLengthsData.body()) {
-            final PacketLengthsBuilder packetLengthsBuilder = new PacketLengthsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> packetLengthsBuilder.setOp(
-                NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> packetLengthsBuilder.setValue((Uint16) dataContainerChild.body()));
-            packetLengths.add(packetLengthsBuilder.build());
-        }
-
-        return packetLengths;
+        return packetLengthsData.body().stream()
+            .map(node -> {
+                final var builder = new PacketLengthsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericTwoByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint16) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<Dscps> createDscpsLengths(final UnkeyedListNode dscpLengthsData) {
-        final List<Dscps> dscpsLengths = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : dscpLengthsData.body()) {
-            final DscpsBuilder dscpsLengthsBuilder = new DscpsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> dscpsLengthsBuilder.setOp(
-                NumericOneByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(
-                dataContainerChild -> dscpsLengthsBuilder.setValue(new Dscp((Uint8) dataContainerChild.body())));
-            dscpsLengths.add(dscpsLengthsBuilder.build());
-        }
-
-        return dscpsLengths;
+        return dscpLengthsData.body().stream()
+            .map(node -> {
+                final var builder = new DscpsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue(new Dscp((Uint8) value.body()));
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<Fragments> createFragments(final UnkeyedListNode fragmentsData) {
-        final List<Fragments> fragments = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : fragmentsData.body()) {
-            final FragmentsBuilder fragmentsBuilder = new FragmentsBuilder();
-            node.findChildByArg(OP_NID).ifPresent(dataContainerChild -> fragmentsBuilder.setOp(
-                BitmaskOperandParser.INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(VALUE_NID).ifPresent(dataContainerChild -> fragmentsBuilder.setValue(
-                createFragment((Set<String>) dataContainerChild.body())));
-            fragments.add(fragmentsBuilder.build());
-        }
-
-        return fragments;
+        return fragmentsData.body().stream()
+            .map(node -> {
+                final var builder = new FragmentsBuilder();
+                final var op = node.childByArg(OP_NID);
+                if (op != null) {
+                    builder.setOp(BitmaskOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(VALUE_NID);
+                if (value != null) {
+                    builder.setValue(createFragment((Set<String>) value.body()));
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static Fragment createFragment(final Set<String> data) {
@@ -456,31 +484,30 @@ public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSeri
     final String encodeFlow(final Flowspec flow) {
         final StringBuilder buffer = new StringBuilder();
         final FlowspecType value = flow.getFlowspecType();
-        if (value instanceof PortCase) {
+        if (value instanceof PortCase port) {
             buffer.append("where port ");
-            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((PortCase) value).getPorts()));
-        } else if (value instanceof DestinationPortCase) {
+            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(port.getPorts()));
+        } else if (value instanceof DestinationPortCase destinationPort) {
             buffer.append("where destination port ");
-            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(
-                ((DestinationPortCase) value).getDestinationPorts()));
-        } else if (value instanceof SourcePortCase) {
+            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(destinationPort.getDestinationPorts()));
+        } else if (value instanceof SourcePortCase sourcePort) {
             buffer.append("where source port ");
-            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((SourcePortCase) value).getSourcePorts()));
-        } else if (value instanceof IcmpTypeCase) {
+            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(sourcePort.getSourcePorts()));
+        } else if (value instanceof IcmpTypeCase icmpType) {
             buffer.append("where ICMP type ");
-            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((IcmpTypeCase) value).getTypes()));
-        } else if (value instanceof IcmpCodeCase) {
+            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(icmpType.getTypes()));
+        } else if (value instanceof IcmpCodeCase icmpCode) {
             buffer.append("where ICMP code ");
-            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((IcmpCodeCase) value).getCodes()));
-        } else if (value instanceof TcpFlagsCase) {
-            buffer.append(stringTcpFlags(((TcpFlagsCase) value).getTcpFlags()));
-        } else if (value instanceof PacketLengthCase) {
+            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(icmpCode.getCodes()));
+        } else if (value instanceof TcpFlagsCase tcpFlags) {
+            buffer.append(stringTcpFlags(tcpFlags.getTcpFlags()));
+        } else if (value instanceof PacketLengthCase packetLength) {
             buffer.append("where packet length ");
-            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((PacketLengthCase) value).getPacketLengths()));
-        } else if (value instanceof DscpCase) {
-            buffer.append(stringDscp(((DscpCase) value).getDscps()));
-        } else if (value instanceof FragmentCase) {
-            buffer.append(stringFragment(((FragmentCase) value).getFragments()));
+            buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(packetLength.getPacketLengths()));
+        } else if (value instanceof DscpCase dscp) {
+            buffer.append(stringDscp(dscp.getDscps()));
+        } else if (value instanceof FragmentCase fragment) {
+            buffer.append(stringFragment(fragment.getFragments()));
         } else {
             stringSpecificFSNlriType(value, buffer);
         }
@@ -608,12 +635,9 @@ public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSeri
         }
         final PathId pathId = readPathId(nlri, builder.getAfi(), builder.getSafi(), constraint);
         final Object[] nlriFields = parseNlri(nlri);
-        builder.setAdvertizedRoutes(
-            new AdvertizedRoutesBuilder()
-                .setDestinationType(
-                    createAdvertizedRoutesDestinationType(nlriFields, pathId)
-                ).build()
-        );
+        builder.setAdvertizedRoutes(new AdvertizedRoutesBuilder()
+            .setDestinationType(createAdvertizedRoutesDestinationType(nlriFields, pathId))
+            .build());
     }
 
     @Override
@@ -624,11 +648,9 @@ public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSeri
         }
         final PathId pathId = readPathId(nlri, builder.getAfi(), builder.getSafi(), constraint);
         final Object[] nlriFields = parseNlri(nlri);
-        builder.setWithdrawnRoutes(
-            new WithdrawnRoutesBuilder()
-                .setDestinationType(
-                    createWithdrawnDestinationType(nlriFields, pathId)
-                ).build()
+        builder.setWithdrawnRoutes(new WithdrawnRoutesBuilder()
+            .setDestinationType(createWithdrawnDestinationType(nlriFields, pathId))
+            .build()
         );
     }
 
index c959c29eab7033b5d5fbc64315c41a8964330e25..86dd1cf95ff5afbe67896873ccd32825172d9fd1 100644 (file)
@@ -13,7 +13,6 @@ import com.google.common.annotations.Beta;
 import com.google.common.collect.Iterables;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Optional;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
 import org.opendaylight.protocol.bgp.parser.spi.PathIdUtil;
@@ -31,7 +30,6 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 
 @Beta
@@ -60,8 +58,8 @@ public abstract class AbstractFlowspecRIBSupport<
     protected DestinationType buildDestination(final Collection<MapEntryNode> routes) {
         final MapEntryNode routesCont = Iterables.getOnlyElement(routes);
         final PathId pathId = PathIdUtil.buildPathId(routesCont, routePathIdNid());
-        return this.nlriParser.createAdvertizedRoutesDestinationType(
-            new Object[] {this.nlriParser.extractFlowspec(routesCont)},
+        return nlriParser.createAdvertizedRoutesDestinationType(
+            new Object[] {nlriParser.extractFlowspec(routesCont)},
             pathId
         );
     }
@@ -70,8 +68,8 @@ public abstract class AbstractFlowspecRIBSupport<
     protected DestinationType buildWithdrawnDestination(final Collection<MapEntryNode> routes) {
         final MapEntryNode routesCont = Iterables.getOnlyElement(routes);
         final PathId pathId = PathIdUtil.buildPathId(routesCont, routePathIdNid());
-        return this.nlriParser.createWithdrawnDestinationType(
-            new Object[] {this.nlriParser.extractFlowspec(Iterables.getOnlyElement(routes))},
+        return nlriParser.createWithdrawnDestinationType(
+            new Object[] {nlriParser.extractFlowspec(Iterables.getOnlyElement(routes))},
             pathId
         );
     }
@@ -87,14 +85,10 @@ public abstract class AbstractFlowspecRIBSupport<
         if (destination == null) {
             return Collections.emptyList();
         }
-        final YangInstanceIdentifier base = routesYangInstanceIdentifier(routesPath);
-
-        final Optional<DataContainerChild> maybePathIdLeaf = destination.findChildByArg(routePathIdNid());
-        final String routeKeyValue = this.nlriParser.stringNlri(destination);
-        final NodeIdentifierWithPredicates routeKey = PathIdUtil.createNidKey(routeQName(), routeKeyTemplate(),
-                routeKeyValue, maybePathIdLeaf);
-        function.apply(tx, base, routeKey, destination, attributes);
 
+        final var routeKey = PathIdUtil.createNidKey(routeQName(), routeKeyTemplate(),
+            nlriParser.stringNlri(destination), destination.findChildByArg(routePathIdNid()));
+        function.apply(tx, routesYangInstanceIdentifier(routesPath), routeKey, destination, attributes);
         return Collections.singletonList(routeKey);
     }
 }
index 29c9c8c743faf6a7a343886c55d237b0857e2cd4..75f57d6dd0ae3d1ed9eedda3b56e08accc2abdd3 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.flowspec.ipv4;
 
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
+import java.util.stream.Collectors;
 import org.opendaylight.protocol.bgp.flowspec.AbstractFlowspecNlriParser;
 import org.opendaylight.protocol.bgp.flowspec.handlers.NumericOneByteOperandParser;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
@@ -26,7 +26,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flow
 import org.opendaylight.yangtools.yang.common.Uint8;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
-import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 
 /**
@@ -38,51 +37,58 @@ public final class FlowspecIpv4NlriParserHelper {
     private static final NodeIdentifier PROTOCOL_IP_NID = new NodeIdentifier(ProtocolIps.QNAME);
 
     private FlowspecIpv4NlriParserHelper() {
-
+        // Hidden on purpose
     }
 
     public static void extractFlowspec(final ChoiceNode fsType, final FlowspecBuilder fsBuilder) {
-        if (fsType.findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new DestinationPrefixCaseBuilder().setDestinationPrefix(
-                    new Ipv4Prefix((String) fsType.findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).get()
-                            .body())).build());
-        } else if (fsType.findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new SourcePrefixCaseBuilder().setSourcePrefix(new Ipv4Prefix((String) fsType
-                    .findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).get().body())).build());
-        } else if (fsType.findChildByArg(PROTOCOL_IP_NID).isPresent()) {
+        final var destPrefix = fsType.childByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID);
+        if (destPrefix != null) {
+            fsBuilder.setFlowspecType(new DestinationPrefixCaseBuilder()
+                .setDestinationPrefix(new Ipv4Prefix((String) destPrefix.body()))
+                .build());
+            return;
+        }
+        final var sourcePrefix = fsType.childByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID);
+        if (sourcePrefix != null) {
+            fsBuilder.setFlowspecType(new SourcePrefixCaseBuilder()
+                .setSourcePrefix(new Ipv4Prefix((String) sourcePrefix.body()))
+                .build());
+            return;
+        }
+        final var protocolIp = fsType.childByArg(PROTOCOL_IP_NID);
+        if (protocolIp != null) {
             fsBuilder.setFlowspecType(new ProtocolIpCaseBuilder()
-                    .setProtocolIps(createProtocolsIps((UnkeyedListNode) fsType.findChildByArg(PROTOCOL_IP_NID).get()))
-                    .build());
+                .setProtocolIps(createProtocolsIps((UnkeyedListNode) protocolIp))
+                .build());
         }
     }
 
     public static void buildFlowspecString(final FlowspecType value, final StringBuilder buffer) {
-        if (value instanceof DestinationPrefixCase) {
-            buffer.append("to ");
-            buffer.append(((DestinationPrefixCase) value).getDestinationPrefix().getValue());
-        } else if (value instanceof SourcePrefixCase) {
-            buffer.append("from ");
-            buffer.append(((SourcePrefixCase) value).getSourcePrefix().getValue());
-        } else if (value instanceof ProtocolIpCase) {
-            buffer.append("where IP protocol ");
-            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((ProtocolIpCase) value).getProtocolIps()));
+        if (value instanceof DestinationPrefixCase destinationPrefix) {
+            buffer.append("to ").append(destinationPrefix.getDestinationPrefix().getValue());
+        } else if (value instanceof SourcePrefixCase sourcePrefix) {
+            buffer.append("from ").append(sourcePrefix.getSourcePrefix().getValue());
+        } else if (value instanceof ProtocolIpCase protocolIp) {
+            buffer.append("where IP protocol ").append(
+                NumericOneByteOperandParser.INSTANCE.toString(protocolIp.getProtocolIps()));
         }
     }
 
     private static List<ProtocolIps> createProtocolsIps(final UnkeyedListNode protocolIpsData) {
-        final List<ProtocolIps> protocolIps = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : protocolIpsData.body()) {
-            final ProtocolIpsBuilder ipsBuilder = new ProtocolIpsBuilder();
-            node.findChildByArg(AbstractFlowspecNlriParser.OP_NID).ifPresent(
-                dataContainerChild -> ipsBuilder.setOp(NumericOneByteOperandParser
-                    .INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(AbstractFlowspecNlriParser.VALUE_NID).ifPresent(
-                dataContainerChild -> ipsBuilder.setValue((Uint8) dataContainerChild.body()));
-            protocolIps.add(ipsBuilder.build());
-        }
-
-        return protocolIps;
+        return protocolIpsData.body().stream()
+            .map(node -> {
+                final var builder = new ProtocolIpsBuilder();
+                final var op = node.childByArg(AbstractFlowspecNlriParser.OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(AbstractFlowspecNlriParser.VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint8) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 }
 
index 3b4e3af1c9412c8553c8bc84dbd35b4a285e40af..a66926711852fb48c129991e7ed680c0859498b1 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.flowspec.ipv6;
 
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
+import java.util.stream.Collectors;
 import org.opendaylight.protocol.bgp.flowspec.AbstractFlowspecNlriParser;
 import org.opendaylight.protocol.bgp.flowspec.handlers.NumericOneByteOperandParser;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
@@ -31,7 +31,6 @@ import org.opendaylight.yangtools.yang.common.Uint32;
 import org.opendaylight.yangtools.yang.common.Uint8;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
-import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 
 public final class FlowspecIpv6NlriParserHelper {
@@ -39,87 +38,98 @@ public final class FlowspecIpv6NlriParserHelper {
     private static final NodeIdentifier FLOW_LABEL_NID = new NodeIdentifier(FlowLabel.QNAME);
 
     private FlowspecIpv6NlriParserHelper() {
-
+        // Hidden on purpose
     }
 
     public static void extractFlowspec(final ChoiceNode fsType, final FlowspecBuilder fsBuilder) {
-        if (fsType.findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).isPresent()) {
+        final var destPrefix = fsType.childByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID);
+        if (destPrefix != null) {
             fsBuilder.setFlowspecType(new DestinationIpv6PrefixCaseBuilder()
-                .setDestinationPrefix(new Ipv6Prefix((String) fsType
-                    .findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).get().body())).build());
-        } else if (fsType.findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).isPresent()) {
-            fsBuilder.setFlowspecType(new SourceIpv6PrefixCaseBuilder().setSourcePrefix(new Ipv6Prefix((String) fsType
-                .findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).get().body())).build());
-        } else if (fsType.findChildByArg(NEXT_HEADER_NID).isPresent()) {
+                .setDestinationPrefix(new Ipv6Prefix((String) destPrefix.body()))
+                .build());
+            return;
+        }
+        final var sourcePrefix = fsType.childByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID);
+        if (sourcePrefix != null) {
+            fsBuilder.setFlowspecType(new SourceIpv6PrefixCaseBuilder()
+                .setSourcePrefix(new Ipv6Prefix((String) sourcePrefix.body()))
+                .build());
+            return;
+        }
+        final var nextHeader = fsType.childByArg(NEXT_HEADER_NID);
+        if (nextHeader != null) {
             fsBuilder.setFlowspecType(new NextHeaderCaseBuilder()
-                .setNextHeaders(createNextHeaders((UnkeyedListNode) fsType.findChildByArg(NEXT_HEADER_NID).get()))
+                .setNextHeaders(createNextHeaders((UnkeyedListNode) nextHeader))
                 .build());
-        } else if (fsType.findChildByArg(FLOW_LABEL_NID).isPresent()) {
+            return;
+        }
+        final var flowLabel = fsType.childByArg(FLOW_LABEL_NID);
+        if (flowLabel != null) {
             fsBuilder.setFlowspecType(new FlowLabelCaseBuilder()
-                .setFlowLabel(createFlowLabels((UnkeyedListNode) fsType.findChildByArg(FLOW_LABEL_NID).get())).build());
+                .setFlowLabel(createFlowLabels((UnkeyedListNode) flowLabel))
+                .build());
         }
     }
 
     public static void buildFlowspecString(final FlowspecType value, final StringBuilder buffer) {
-        if (value instanceof DestinationIpv6PrefixCase) {
-            buffer.append("to ");
-            buffer.append(((DestinationIpv6PrefixCase) value).getDestinationPrefix().getValue());
-        } else if (value instanceof SourceIpv6PrefixCase) {
-            buffer.append("from ");
-            buffer.append(((SourceIpv6PrefixCase) value).getSourcePrefix().getValue());
-        } else if (value instanceof NextHeaderCase) {
-            buffer.append("where next header ");
-            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((NextHeaderCase) value).getNextHeaders()));
-        } else if (value instanceof FlowLabelCase) {
-            buffer.append("where flow label ");
-            buffer.append(stringFlowLabel(((FlowLabelCase) value).getFlowLabel()));
+        if (value instanceof DestinationIpv6PrefixCase destinationIpv6) {
+            buffer.append("to ").append(destinationIpv6.getDestinationPrefix().getValue());
+        } else if (value instanceof SourceIpv6PrefixCase sourceIpv6) {
+            buffer.append("from ").append(sourceIpv6.getSourcePrefix().getValue());
+        } else if (value instanceof NextHeaderCase nextHeader) {
+            buffer.append("where next header ").append(
+                NumericOneByteOperandParser.INSTANCE.toString(nextHeader.getNextHeaders()));
+        } else if (value instanceof FlowLabelCase flowLabel) {
+            buffer.append("where flow label ").append(stringFlowLabel(flowLabel.getFlowLabel()));
         }
     }
 
     private static List<NextHeaders> createNextHeaders(final UnkeyedListNode nextHeadersData) {
-        final List<NextHeaders> nextHeaders = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : nextHeadersData.body()) {
-            final NextHeadersBuilder nextHeadersBuilder = new NextHeadersBuilder();
-            node.findChildByArg(AbstractFlowspecNlriParser.OP_NID).ifPresent(
-                dataContainerChild -> nextHeadersBuilder.setOp(NumericOneByteOperandParser
-                    .INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(AbstractFlowspecNlriParser.VALUE_NID).ifPresent(
-                dataContainerChild -> nextHeadersBuilder.setValue((Uint8) dataContainerChild.body()));
-            nextHeaders.add(nextHeadersBuilder.build());
-        }
-
-        return nextHeaders;
+        return nextHeadersData.body().stream()
+            .map(node -> {
+                final var builder = new NextHeadersBuilder();
+                final var op = node.childByArg(AbstractFlowspecNlriParser.OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(AbstractFlowspecNlriParser.VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint8) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static List<FlowLabel> createFlowLabels(final UnkeyedListNode flowLabelsData) {
-        final List<FlowLabel> flowLabels = new ArrayList<>();
-
-        for (final UnkeyedListEntryNode node : flowLabelsData.body()) {
-            final FlowLabelBuilder flowLabelsBuilder = new FlowLabelBuilder();
-            node.findChildByArg(AbstractFlowspecNlriParser.OP_NID).ifPresent(
-                dataContainerChild -> flowLabelsBuilder.setOp(NumericOneByteOperandParser
-                    .INSTANCE.create((Set<String>) dataContainerChild.body())));
-            node.findChildByArg(AbstractFlowspecNlriParser.VALUE_NID).ifPresent(
-                dataContainerChild -> flowLabelsBuilder.setValue((Uint32) dataContainerChild.body()));
-            flowLabels.add(flowLabelsBuilder.build());
-        }
-
-        return flowLabels;
+        return flowLabelsData.body().stream()
+            .map(node -> {
+                final var builder = new FlowLabelBuilder();
+                final var op = node.childByArg(AbstractFlowspecNlriParser.OP_NID);
+                if (op != null) {
+                    builder.setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) op.body()));
+                }
+                final var value = node.childByArg(AbstractFlowspecNlriParser.VALUE_NID);
+                if (value != null) {
+                    builder.setValue((Uint32) value.body());
+                }
+                return builder.build();
+            })
+            .collect(Collectors.toList());
     }
 
     private static String stringFlowLabel(final List<FlowLabel> list) {
-        final StringBuilder buffer = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
         boolean isFirst = true;
-        for (final FlowLabel item : list) {
-            buffer.append(NumericOneByteOperandParser.INSTANCE.toString(item.getOp(), isFirst));
-            buffer.append(item.getValue());
-            buffer.append(' ');
+        for (var label : list) {
+            sb.append(NumericOneByteOperandParser.INSTANCE.toString(label.getOp(), isFirst));
+            sb.append(label.getValue());
+            sb.append(' ');
             if (isFirst) {
                 isFirst = false;
             }
         }
-        return buffer.toString();
+        return sb.toString();
     }
 }
 
index de8e7ba566ed3a55a7c9049182586089192c9d5c..f6453d5923e567cce29883b564bb0869df8d8159 100644 (file)
@@ -43,12 +43,12 @@ final class IPv4RIBSupport extends AbstractIPRibSupport<Ipv4RoutesCase, Ipv4Rout
     }
 
     private List<Ipv4Prefixes> extractPrefixes(final Collection<MapEntryNode> routes) {
-        final List<Ipv4Prefixes> prefs = new ArrayList<>(routes.size());
-        for (final MapEntryNode route : routes) {
-            final String prefix = (String) NormalizedNodes.findNode(route, routePrefixIdentifier()).get().body();
-            final Ipv4PrefixesBuilder prefixBuilder = new Ipv4PrefixesBuilder().setPrefix(new Ipv4Prefix(prefix));
-            prefixBuilder.setPathId(PathIdUtil.buildPathId(route, routePathIdNid()));
-            prefs.add(prefixBuilder.build());
+        final var prefs = new ArrayList<Ipv4Prefixes>(routes.size());
+        for (var route : routes) {
+            final var prefix = (String) NormalizedNodes.findNode(route, routePrefixIdentifier()).orElseThrow().body();
+            prefs.add(new Ipv4PrefixesBuilder()
+                .setPrefix(new Ipv4Prefix(prefix)).setPathId(PathIdUtil.buildPathId(route, routePathIdNid()))
+                .build());
         }
         return prefs;
     }
index 2476c2c62ffbe1ef038037a8db6ef9c0c777357c..b1020451f6b90fba3748b36aa1bfdb195c8d43d5 100644 (file)
@@ -55,11 +55,12 @@ final class IPv6RIBSupport extends AbstractIPRibSupport<Ipv6RoutesCase, Ipv6Rout
     }
 
     private List<Ipv6Prefixes> extractPrefixes(final Collection<MapEntryNode> routes) {
-        final List<Ipv6Prefixes> prefs = new ArrayList<>(routes.size());
-        for (final MapEntryNode route : routes) {
-            final String prefix = (String) NormalizedNodes.findNode(route, routePrefixIdentifier()).get().body();
-            prefs.add(new Ipv6PrefixesBuilder().setPathId(PathIdUtil.buildPathId(route, routePathIdNid()))
-                    .setPrefix(new Ipv6Prefix(prefix)).build());
+        final var prefs = new ArrayList<Ipv6Prefixes>(routes.size());
+        for (var route : routes) {
+            final var prefix = (String) NormalizedNodes.findNode(route, routePrefixIdentifier()).orElseThrow().body();
+            prefs.add(new Ipv6PrefixesBuilder()
+                .setPathId(PathIdUtil.buildPathId(route, routePathIdNid())).setPrefix(new Ipv6Prefix(prefix))
+                .build());
         }
         return prefs;
     }
index 05fae13cf5f70ae3655ce23cb17306224db9ca48..aaa2cacc01e4e6979519bb02925a53c30719a40f 100644 (file)
@@ -11,10 +11,9 @@ import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.List;
-import java.util.Optional;
 import java.util.stream.Collectors;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
 import org.opendaylight.protocol.bgp.linkstate.impl.nlri.LinkstateNlriParser;
@@ -77,18 +76,15 @@ public final class LinkstateRIBSupport
                                                                           final ContainerNode destination,
                                                                           final ContainerNode attributes,
                                                                           final ApplyRoute function) {
-        if (destination != null) {
-            return processRoute(destination.findChildByArg(LinkstateRIBSupport.NLRI_ROUTES_LIST), routesPath,
-                attributes, function, tx);
-        }
-        return Collections.emptyList();
+        return destination == null ? List.of()
+            : processRoute(destination.childByArg(LinkstateRIBSupport.NLRI_ROUTES_LIST), routesPath, attributes,
+                function, tx);
     }
 
-    private List<NodeIdentifierWithPredicates> processRoute(final Optional<DataContainerChild> maybeRoutes,
+    private List<NodeIdentifierWithPredicates> processRoute(final @Nullable DataContainerChild routes,
             final YangInstanceIdentifier routesPath, final ContainerNode attributes, final ApplyRoute function,
             final DOMDataTreeWriteTransaction tx) {
-        if (maybeRoutes.isPresent()) {
-            final DataContainerChild routes = maybeRoutes.get();
+        if (routes != null) {
             if (routes instanceof UnkeyedListNode) {
                 final YangInstanceIdentifier base = routesYangInstanceIdentifier(routesPath);
                 final Collection<UnkeyedListEntryNode> routesList = ((UnkeyedListNode) routes).body();
@@ -102,7 +98,7 @@ public final class LinkstateRIBSupport
             }
             LOG.warn("Routes {} are not a map", routes);
         }
-        return Collections.emptyList();
+        return List.of();
     }
 
     @Override
index 0fcd3f953ca3fd900618410b3169206cd3b42ff3..5b021a75d5941344d65014d2dea6282be97538e2 100644 (file)
@@ -65,9 +65,11 @@ public final class LinkNlriParser extends AbstractNlriTypeCodec {
     static LinkDescriptors serializeLinkDescriptors(final ContainerNode descriptors) {
         final LinkDescriptorsBuilder linkDescBuilder = new LinkDescriptorsBuilder();
 
-        if (descriptors.childByArg(LINK_LOCAL_NID) != null && descriptors.childByArg(LINK_REMOTE_NID) != null) {
-            linkDescBuilder.setLinkLocalIdentifier((Uint32) descriptors.findChildByArg(LINK_LOCAL_NID).get().body());
-            linkDescBuilder.setLinkRemoteIdentifier((Uint32) descriptors.findChildByArg(LINK_REMOTE_NID).get().body());
+        final var descLocal = descriptors.childByArg(LINK_LOCAL_NID);
+        final var descRemote = descriptors.childByArg(LINK_REMOTE_NID);
+        if (descLocal != null && descRemote != null) {
+            linkDescBuilder.setLinkLocalIdentifier((Uint32) descLocal.body());
+            linkDescBuilder.setLinkRemoteIdentifier((Uint32) descRemote.body());
         }
         ifPresentApply(descriptors, IPV4_IFACE_NID,
             value -> linkDescBuilder.setIpv4InterfaceAddress(new Ipv4InterfaceIdentifier((String) value)));
index 52247fefc81236f36eedeca429ab4821c6db6546..bb27d11ffd1859c59052bf6c6356bbbd32c9ff17 100644 (file)
@@ -95,7 +95,7 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
     private List<CLinkstateDestination> parseNlri(final ByteBuf nlri) {
         final List<CLinkstateDestination> dests = new ArrayList<>();
         while (nlri.isReadable()) {
-            final CLinkstateDestination destination = this.nlriTypeReg.parseNlriType(nlri);
+            final CLinkstateDestination destination = nlriTypeReg.parseNlriType(nlri);
             if (destination == null) {
                 continue;
             }
@@ -151,7 +151,7 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
                     = (DestinationLinkstateCase) withdrawnRoutes.getDestinationType();
             for (final CLinkstateDestination linkstateDestinationCase : linkstateCase.getDestinationLinkstate()
                     .getCLinkstateDestination()) {
-                this.nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
+                nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
             }
         }
     }
@@ -167,111 +167,99 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
                         .bgp.linkstate.rev200120.update.attributes.mp.reach.nlri.advertized.routes.destination.type
                         .DestinationLinkstateCase) advertizedRoutes.getDestinationType();
 
-            for (final CLinkstateDestination linkstateDestinationCase : linkstateCase.getDestinationLinkstate()
-                    .getCLinkstateDestination()) {
-                this.nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
+            for (var linkstateDestinationCase : linkstateCase.getDestinationLinkstate().getCLinkstateDestination()) {
+                nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
             }
         }
     }
 
     // FIXME : use codec
     private static int domProtocolIdValue(final String protocolId) {
-        switch (protocolId) {
-            case "isis-level1":
-                return ProtocolId.IsisLevel1.getIntValue();
-            case "isis-level2":
-                return ProtocolId.IsisLevel2.getIntValue();
-            case "ospf":
-                return ProtocolId.Ospf.getIntValue();
-            case "direct":
-                return ProtocolId.Direct.getIntValue();
-            case "static":
-                return ProtocolId.Static.getIntValue();
-            case "ospf-v3":
-                return ProtocolId.OspfV3.getIntValue();
-            case "rsvp-te":
-                return ProtocolId.RsvpTe.getIntValue();
-            case "bgp-epe":
-                return ProtocolId.BgpEpe.getIntValue();
-            case "segment-routing":
-                return ProtocolId.SegmentRouting.getIntValue();
-            default:
-                return 0;
-        }
+        return switch (protocolId) {
+            case "isis-level1" -> ProtocolId.IsisLevel1.getIntValue();
+            case "isis-level2" -> ProtocolId.IsisLevel2.getIntValue();
+            case "ospf" -> ProtocolId.Ospf.getIntValue();
+            case "direct" -> ProtocolId.Direct.getIntValue();
+            case "static" -> ProtocolId.Static.getIntValue();
+            case "ospf-v3" -> ProtocolId.OspfV3.getIntValue();
+            case "rsvp-te" -> ProtocolId.RsvpTe.getIntValue();
+            case "bgp-epe" -> ProtocolId.BgpEpe.getIntValue();
+            case "segment-routing" -> ProtocolId.SegmentRouting.getIntValue();
+            default -> 0;
+        };
     }
 
     public static CLinkstateDestination extractLinkstateDestination(final DataContainerNode linkstate) {
-        final CLinkstateDestinationBuilder builder = new CLinkstateDestinationBuilder();
-        serializeCommonParts(builder, linkstate);
-
-        final ChoiceNode objectType = (ChoiceNode) linkstate.findChildByArg(OBJECT_TYPE_NID).get();
-        if (objectType.findChildByArg(ADVERTISING_NODE_DESCRIPTORS_NID).isPresent()) {
-            serializeAdvertisedNodeDescriptor(builder, objectType);
-        } else if (objectType.findChildByArg(LOCAL_NODE_DESCRIPTORS_NID).isPresent()) {
-            serializeLocalNodeDescriptor(builder, objectType);
-        } else if (objectType.findChildByArg(NODE_DESCRIPTORS_NID).isPresent()) {
-            serializeNodeDescriptor(builder, objectType);
-        } else if (AbstractTeLspNlriCodec.isTeLsp(objectType)) {
-            builder.setObjectType(AbstractTeLspNlriCodec.serializeTeLsp(objectType));
-        } else {
-            LOG.warn("Unknown Object Type: {}.", objectType);
+        final var builder = new CLinkstateDestinationBuilder();
+        // serialize common parts
+        final var distinguisher = linkstate.childByArg(DISTINGUISHER_NID);
+        if (distinguisher != null) {
+            builder.setRouteDistinguisher(RouteDistinguisherUtil.parseRouteDistinguisher(distinguisher.body()));
+        }
+        final var protocolId = linkstate.childByArg(PROTOCOL_ID_NID);
+        if (protocolId != null) {
+            // DOM representation contains values as are in the model, not as are in generated enum
+            builder.setProtocolId(ProtocolId.forValue(domProtocolIdValue((String) protocolId.body())));
+        }
+        final var identifier = linkstate.childByArg(IDENTIFIER_NID);
+        if (identifier != null) {
+            builder.setIdentifier(new Identifier((Uint64) identifier.body()));
         }
-        return builder.build();
-    }
 
-    private static void serializeNodeDescriptor(final CLinkstateDestinationBuilder builder,
-            final ChoiceNode objectType) {
-        final NodeCaseBuilder nodeBuilder = new NodeCaseBuilder();
-        // node descriptors
-        nodeBuilder.setNodeDescriptors(NodeNlriParser
-                .serializeNodeDescriptors((ContainerNode) objectType.findChildByArg(NODE_DESCRIPTORS_NID).get()));
-        builder.setObjectType(nodeBuilder.build());
+        return builder
+            .setObjectType(serializeObjectType((ChoiceNode) linkstate.getChildByArg(OBJECT_TYPE_NID)))
+            .build();
     }
 
-    private static void serializeLocalNodeDescriptor(final CLinkstateDestinationBuilder builder,
-            final ChoiceNode objectType) {
-        // link local node descriptors
-        final LinkCaseBuilder linkBuilder = new LinkCaseBuilder();
+    private static ObjectType serializeObjectType(final ChoiceNode objectType) {
+        final var advNode = objectType.childByArg(ADVERTISING_NODE_DESCRIPTORS_NID);
+        if (advNode != null) {
+            // prefix node descriptors
+            final var builder = new PrefixCaseBuilder()
+                .setAdvertisingNodeDescriptors(NodeNlriParser.serializeAdvNodeDescriptors((ContainerNode) advNode));
+
+            // prefix descriptors
+            final var prefix = objectType.childByArg(PREFIX_DESCRIPTORS_NID);
+            if (prefix != null) {
+                builder.setPrefixDescriptors(
+                    AbstractPrefixNlriParser.serializePrefixDescriptors((ContainerNode) prefix));
+            }
+            return builder.build();
+        }
 
-        linkBuilder.setLocalNodeDescriptors(NodeNlriParser.serializeLocalNodeDescriptors((ContainerNode) objectType
-                .findChildByArg(LOCAL_NODE_DESCRIPTORS_NID).get()));
-        // link remote node descriptors
-        if (objectType.findChildByArg(REMOTE_NODE_DESCRIPTORS_NID).isPresent()) {
-            linkBuilder.setRemoteNodeDescriptors(NodeNlriParser.serializeRemoteNodeDescriptors(
-                (ContainerNode) objectType.findChildByArg(REMOTE_NODE_DESCRIPTORS_NID).get()));
+        final var localNode = objectType.childByArg(LOCAL_NODE_DESCRIPTORS_NID);
+        if (localNode != null) {
+            // link local node descriptors
+            final var builder = new LinkCaseBuilder()
+                .setLocalNodeDescriptors(NodeNlriParser.serializeLocalNodeDescriptors((ContainerNode) localNode));
+            // link remote node descriptors
+            final var remoteNode = objectType.childByArg(REMOTE_NODE_DESCRIPTORS_NID);
+            if (remoteNode != null) {
+                builder.setRemoteNodeDescriptors(
+                    NodeNlriParser.serializeRemoteNodeDescriptors((ContainerNode) remoteNode));
+            }
+            // link descriptors
+            final var link = objectType.childByArg(LINK_DESCRIPTORS_NID);
+            if (link != null) {
+                builder.setLinkDescriptors(LinkNlriParser.serializeLinkDescriptors((ContainerNode) link));
+            }
+            return builder.build();
         }
-        // link descriptors
-        objectType.findChildByArg(LINK_DESCRIPTORS_NID).ifPresent(
-            dataContainerChild -> linkBuilder.setLinkDescriptors(
-                LinkNlriParser.serializeLinkDescriptors((ContainerNode) dataContainerChild)));
-        builder.setObjectType(linkBuilder.build());
-    }
 
-    private static void serializeAdvertisedNodeDescriptor(final CLinkstateDestinationBuilder builder,
-            final ChoiceNode objectType) {
-        // prefix node descriptors
-        final PrefixCaseBuilder prefixBuilder = new PrefixCaseBuilder();
-        prefixBuilder.setAdvertisingNodeDescriptors(NodeNlriParser.serializeAdvNodeDescriptors(
-            (ContainerNode) objectType.findChildByArg(ADVERTISING_NODE_DESCRIPTORS_NID).get()));
+        final var node = objectType.childByArg(NODE_DESCRIPTORS_NID);
+        if (node != null) {
+            // node descriptors
+            return new NodeCaseBuilder()
+                .setNodeDescriptors(NodeNlriParser.serializeNodeDescriptors((ContainerNode) node))
+                .build();
+        }
 
-        // prefix descriptors
-        objectType.findChildByArg(PREFIX_DESCRIPTORS_NID).ifPresent(
-            dataContainerChild -> prefixBuilder.setPrefixDescriptors(
-                AbstractPrefixNlriParser.serializePrefixDescriptors((ContainerNode) dataContainerChild)));
-        builder.setObjectType(prefixBuilder.build());
-    }
+        final var teLsp = AbstractTeLspNlriCodec.serializeObjectType(objectType);
+        if (teLsp != null) {
+            return teLsp;
+        }
 
-    private static void serializeCommonParts(final CLinkstateDestinationBuilder builder,
-            final DataContainerNode linkstate) {
-        // serialize common parts
-        linkstate.findChildByArg(DISTINGUISHER_NID).ifPresent(
-            dataContainerChild -> builder.setRouteDistinguisher(
-                RouteDistinguisherUtil.parseRouteDistinguisher(dataContainerChild.body())));
-        linkstate.findChildByArg(PROTOCOL_ID_NID).ifPresent(
-            // DOM representation contains values as are in the model, not as are in generated enum
-            dataContainerChild -> builder.setProtocolId(
-                ProtocolId.forValue(domProtocolIdValue((String) dataContainerChild.body()))));
-        linkstate.findChildByArg(IDENTIFIER_NID).ifPresent(
-            dataContainerChild -> builder.setIdentifier(new Identifier((Uint64) dataContainerChild.body())));
+        LOG.warn("Ignoring unknown Object Type: {}.", objectType);
+        return null;
     }
 }
index 4faa257929ab1eaa63513f4a748afce2fbd1cf86..5deacf6d50473b5638cf3408a2a2f5fdfe25c4fd 100644 (file)
@@ -122,50 +122,51 @@ public final class NodeNlriParser extends AbstractNlriTypeCodec {
     private static IsisNodeCase serializeIsisNode(final ContainerNode isis) {
         return new IsisNodeCaseBuilder()
             .setIsisNode(new IsisNodeBuilder()
-                .setIsoSystemId(new IsoSystemIdentifier((byte[]) isis.findChildByArg(ISO_SYSTEM_NID).get().body()))
+                .setIsoSystemId(new IsoSystemIdentifier((byte[]) isis.getChildByArg(ISO_SYSTEM_NID).body()))
                 .build())
             .build();
     }
 
     private static IsisPseudonodeCase serializeIsisPseudoNode(final ContainerNode pseudoIsisNode) {
         final IsIsRouterIdentifierBuilder isisRouterId = new IsIsRouterIdentifierBuilder();
-        if (pseudoIsisNode.findChildByArg(ISIS_ROUTER_NID).isPresent()) {
-            final ContainerNode isisRouterNid = (ContainerNode) pseudoIsisNode.findChildByArg(ISIS_ROUTER_NID).get();
-            if (isisRouterNid.findChildByArg(ISO_SYSTEM_NID).isPresent()) {
-                isisRouterId.setIsoSystemId(
-                    new IsoSystemIdentifier((byte[]) isisRouterNid.findChildByArg(ISO_SYSTEM_NID).get().body()));
+        final var isisRouterNid = pseudoIsisNode.childByArg(ISIS_ROUTER_NID);
+        if (isisRouterNid != null) {
+            final var isoSystemId = ((ContainerNode) isisRouterNid).childByArg(ISO_SYSTEM_NID);
+            if (isoSystemId != null) {
+                isisRouterId.setIsoSystemId(new IsoSystemIdentifier((byte[]) isoSystemId.body()));
             }
         }
 
-        final IsisPseudonodeBuilder nodeBuilder = new IsisPseudonodeBuilder();
-        nodeBuilder.setIsIsRouterIdentifier(isisRouterId.build());
+        final var psn = pseudoIsisNode.childByArg(PSN_NID);
 
-        if (pseudoIsisNode.findChildByArg(PSN_NID).isPresent()) {
-            nodeBuilder.setPsn((Uint8) pseudoIsisNode.findChildByArg(PSN_NID).get().body());
-        } else {
-            nodeBuilder.setPsn(Uint8.ZERO);
-        }
-
-        return new IsisPseudonodeCaseBuilder().setIsisPseudonode(nodeBuilder.build()).build();
+        return new IsisPseudonodeCaseBuilder()
+            .setIsisPseudonode(new IsisPseudonodeBuilder()
+                .setIsIsRouterIdentifier(isisRouterId.build())
+                .setPsn(psn == null ? Uint8.ZERO : (Uint8) psn.body())
+                .build())
+            .build();
     }
 
     private static OspfNodeCase serializeOspfNode(final ContainerNode ospf) {
-        final OspfNodeCaseBuilder builder = new OspfNodeCaseBuilder();
-        ospf.findChildByArg(OSPF_ROUTER_NID)
-            .map(routerId -> new OspfNodeBuilder().setOspfRouterId((Uint32) routerId.body()).build())
-            .ifPresent(builder::setOspfNode);
+        final var builder = new OspfNodeCaseBuilder();
+        final var ospfRouter = ospf.childByArg(OSPF_ROUTER_NID);
+        if (ospfRouter != null) {
+            builder.setOspfNode(new OspfNodeBuilder().setOspfRouterId((Uint32) ospfRouter.body()).build());
+        }
         return builder.build();
     }
 
     private static CRouterIdentifier serializeOspfPseudoNode(final ContainerNode ospfPseudonode) {
-        final OspfPseudonodeBuilder nodeBuilder = new OspfPseudonodeBuilder();
+        final var nodeBuilder = new OspfPseudonodeBuilder();
 
-        ospfPseudonode.findChildByArg(LAN_IFACE_NID)
-            .map(lanIface -> new OspfInterfaceIdentifier((Uint32) lanIface.body()))
-            .ifPresent(nodeBuilder::setLanInterface);
-        ospfPseudonode.findChildByArg(OSPF_ROUTER_NID)
-            .map(ospfRouter -> (Uint32) ospfRouter.body())
-            .ifPresent(nodeBuilder::setOspfRouterId);
+        final var lanIface = ospfPseudonode.childByArg(LAN_IFACE_NID);
+        if (lanIface != null) {
+            nodeBuilder.setLanInterface(new OspfInterfaceIdentifier((Uint32) lanIface.body()));
+        }
+        final var ospfRouter = ospfPseudonode.childByArg(OSPF_ROUTER_NID);
+        if (ospfRouter != null) {
+            nodeBuilder.setOspfRouterId((Uint32) ospfRouter.body());
+        }
 
         return new OspfPseudonodeCaseBuilder()
             .setOspfPseudonode(nodeBuilder.build())
@@ -196,28 +197,28 @@ public final class NodeNlriParser extends AbstractNlriTypeCodec {
     }
 
     private static AsNumber serializeAsNumber(final ContainerNode descriptorsData) {
-        return descriptorsData.findChildByArg(AS_NUMBER_NID).map(
-            dataContainerChild -> new AsNumber((Uint32) dataContainerChild.body())).orElse(null);
+        final var asNumber = descriptorsData.childByArg(AS_NUMBER_NID);
+        return asNumber == null ? null : new AsNumber((Uint32) asNumber.body());
     }
 
     private static DomainIdentifier serializeDomainId(final ContainerNode descriptorsData) {
-        return descriptorsData.findChildByArg(DOMAIN_NID).map(
-            dataContainerChild -> new DomainIdentifier((Uint32) dataContainerChild.body())).orElse(null);
+        final var domain = descriptorsData.childByArg(DOMAIN_NID);
+        return domain == null ? null : new DomainIdentifier((Uint32) domain.body());
     }
 
     private static AreaIdentifier serializeAreaId(final ContainerNode descriptorsData) {
-        return descriptorsData.findChildByArg(AREA_NID).map(
-            dataContainerChild -> new AreaIdentifier((Uint32) dataContainerChild.body())).orElse(null);
+        final var area = descriptorsData.childByArg(AREA_NID);
+        return area == null ? null : new AreaIdentifier((Uint32) area.body());
     }
 
     private static Ipv4AddressNoZone serializeBgpRouterId(final ContainerNode descriptorsData) {
-        return descriptorsData.findChildByArg(BGP_ROUTER_NID).map(
-            dataContainerChild -> new Ipv4AddressNoZone((String) dataContainerChild.body())).orElse(null);
+        final var bgpRouter = descriptorsData.childByArg(BGP_ROUTER_NID);
+        return bgpRouter == null ? null : new Ipv4AddressNoZone((String) bgpRouter.body());
     }
 
     private static AsNumber serializeMemberAsn(final ContainerNode descriptorsData) {
-        return descriptorsData.findChildByArg(MEMBER_ASN_NID).map(
-            dataContainerChild -> new AsNumber((Uint32) dataContainerChild.body())).orElse(null);
+        final var memberAsn = descriptorsData.childByArg(MEMBER_ASN_NID);
+        return memberAsn == null ? null : new AsNumber((Uint32) memberAsn.body());
     }
 
     static LocalNodeDescriptors serializeLocalNodeDescriptors(final ContainerNode descriptorsData) {
index 720c6b977b2bbce09425603092894dda3e7464cd..c1d12787f8dce88b59525535256490b22401e98b 100644 (file)
@@ -43,8 +43,7 @@ public final class MultiTopoIdTlvParser implements LinkstateTlvParser<TopologyId
     }
 
     public static TopologyIdentifier serializeModel(final ContainerNode prefixDesc) {
-        return prefixDesc.findChildByArg(TlvUtil.MULTI_TOPOLOGY_NID)
-                .map(child -> new TopologyIdentifier((Uint16) child.body()))
-                .orElse(null);
+        final var multiTopology = prefixDesc.childByArg(TlvUtil.MULTI_TOPOLOGY_NID);
+        return multiTopology == null ? null : new TopologyIdentifier((Uint16) multiTopology.body());
     }
 }
index 4dd48314c40fe22b7e753c7165e99ec8d909d3c4..e7db6f62fd86481584be8f5609e88db323329841 100644 (file)
@@ -43,28 +43,20 @@ public final class OspfRouteTlvParser implements LinkstateTlvParser<OspfRouteTyp
     }
 
     public static OspfRouteType serializeModel(final ContainerNode prefixDesc) {
-        return prefixDesc.findChildByArg(OSPF_ROUTE_NID).map(
-            dataContainerChild -> OspfRouteType.forValue(domOspfRouteTypeValue((String) dataContainerChild.body())))
-            .orElse(null);
+        final var ospfRoute = prefixDesc.childByArg(OSPF_ROUTE_NID);
+        return ospfRoute == null ? null : OspfRouteType.forValue(domOspfRouteTypeValue((String) ospfRoute.body()));
     }
 
     // FIXME : use codec
     private static int domOspfRouteTypeValue(final String ospfRouteType) {
-        switch (ospfRouteType) {
-            case "intra-area":
-                return OspfRouteType.IntraArea.getIntValue();
-            case "inter-area":
-                return OspfRouteType.InterArea.getIntValue();
-            case "external1":
-                return OspfRouteType.External1.getIntValue();
-            case "external2":
-                return OspfRouteType.External2.getIntValue();
-            case "nssa1":
-                return OspfRouteType.Nssa1.getIntValue();
-            case "nssa2":
-                return OspfRouteType.Nssa2.getIntValue();
-            default:
-                return 0;
-        }
+        return switch (ospfRouteType) {
+            case "intra-area" -> OspfRouteType.IntraArea.getIntValue();
+            case "inter-area" -> OspfRouteType.InterArea.getIntValue();
+            case "external1" -> OspfRouteType.External1.getIntValue();
+            case "external2" -> OspfRouteType.External2.getIntValue();
+            case "nssa1" -> OspfRouteType.Nssa1.getIntValue();
+            case "nssa2" -> OspfRouteType.Nssa2.getIntValue();
+            default -> 0;
+        };
     }
 }
index f203fd29dc8402cffab322bc7eb4307b28c70148..e27e2c0dc6145c0f5aa57572b79b7ff284c86f23 100644 (file)
@@ -72,14 +72,15 @@ public final class ReachTlvParser implements LinkstateTlvParser.LinkstateTlvSeri
     }
 
     public static IpPrefix serializeModel(final ContainerNode prefixDesc) {
-        return prefixDesc.findChildByArg(IP_REACH_NID)
-                .map(child -> {
-                    final String prefix = (String) child.body();
-                    // Get the prefix length from the string to determine if it is an IPv4 or an IPv6 prefix
-                    final int length = Ipv4Util.getPrefixLengthBytes(prefix);
-                    return length <= Ipv4Util.IP4_LENGTH ? new IpPrefix(new Ipv4Prefix(prefix))
-                        : new IpPrefix(new Ipv6Prefix(prefix));
-                })
-                .orElse(null);
+        final var ipReach = prefixDesc.childByArg(IP_REACH_NID);
+        if (ipReach == null) {
+            return null;
+        }
+
+        final String prefix = (String) ipReach.body();
+        // Get the prefix length from the string to determine if it is an IPv4 or an IPv6 prefix
+        final int length = Ipv4Util.getPrefixLengthBytes(prefix);
+        return length <= Ipv4Util.IP4_LENGTH ? new IpPrefix(new Ipv4Prefix(prefix))
+            : new IpPrefix(new Ipv6Prefix(prefix));
     }
 }
index 79fcfe152350ac0b679cab52849ba642f5a9ce1d..fe4d8f8c7dc5488a5f623140c2b171947d90e63d 100644 (file)
@@ -8,10 +8,11 @@
 package org.opendaylight.protocol.bgp.linkstate.spi;
 
 import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Verify.verifyNotNull;
 
 import com.google.common.annotations.VisibleForTesting;
 import io.netty.buffer.ByteBuf;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.protocol.util.Ipv4Util;
 import org.opendaylight.protocol.util.Ipv6Util;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
@@ -58,35 +59,45 @@ public abstract class AbstractTeLspNlriCodec extends AbstractNlriTypeCodec {
     @VisibleForTesting
     public static final NodeIdentifier ADDRESS_FAMILY = NodeIdentifier.create(AddressFamily.QNAME);
 
+    @Deprecated(forRemoval = true)
     public static boolean isTeLsp(final ChoiceNode objectType) {
         return objectType.childByArg(ADDRESS_FAMILY) != null;
     }
 
+    @Deprecated(forRemoval = true)
     public static TeLspCase serializeTeLsp(final ChoiceNode objectType) {
-        final ChoiceNode addressFamily = (ChoiceNode) verifyNotNull(objectType.childByArg(ADDRESS_FAMILY));
-        return new TeLspCaseBuilder()
-                .setLspId(new LspId((Uint32) verifyNotNull(objectType.childByArg(LSP_ID)).body()))
-                .setTunnelId(new TunnelId((Uint16) verifyNotNull(objectType.childByArg(TUNNEL_ID)).body()))
-                .setAddressFamily(serializeAddressFamily(addressFamily,
-                    addressFamily.childByArg(IPV4_TUNNEL_SENDER_ADDRESS) != null))
-                .build();
+        return serializeObjectType(objectType, (ChoiceNode) objectType.getChildByArg(ADDRESS_FAMILY));
     }
 
     private static AddressFamily serializeAddressFamily(final ChoiceNode addressFamily, final boolean ipv4Case) {
         if (ipv4Case) {
             return new Ipv4CaseBuilder()
                 .setIpv4TunnelSenderAddress(new Ipv4AddressNoZone(
-                    (String) verifyNotNull(addressFamily.childByArg(IPV4_TUNNEL_SENDER_ADDRESS)).body()))
+                    (String) addressFamily.getChildByArg(IPV4_TUNNEL_SENDER_ADDRESS).body()))
                 .setIpv4TunnelEndpointAddress(new Ipv4AddressNoZone(
-                    (String) verifyNotNull(addressFamily.childByArg(IPV4_TUNNEL_ENDPOINT_ADDRESS)).body()))
+                    (String) addressFamily.getChildByArg(IPV4_TUNNEL_ENDPOINT_ADDRESS).body()))
                 .build();
         }
 
         return new Ipv6CaseBuilder()
             .setIpv6TunnelSenderAddress(new Ipv6AddressNoZone(
-                (String) verifyNotNull(addressFamily.childByArg(IPV6_TUNNEL_SENDER_ADDRESS)).body()))
+                (String) addressFamily.getChildByArg(IPV6_TUNNEL_SENDER_ADDRESS).body()))
             .setIpv6TunnelEndpointAddress(new Ipv6AddressNoZone(
-                (String) verifyNotNull(addressFamily.childByArg(IPV6_TUNNEL_ENDPOINT_ADDRESS)).body()))
+                (String) addressFamily.getChildByArg(IPV6_TUNNEL_ENDPOINT_ADDRESS).body()))
+            .build();
+    }
+
+    public static @Nullable TeLspCase serializeObjectType(final ChoiceNode objectType) {
+        final var addressFamily = objectType.childByArg(ADDRESS_FAMILY);
+        return addressFamily == null ? null : serializeObjectType(objectType, (ChoiceNode) addressFamily);
+    }
+
+    private static @NonNull TeLspCase serializeObjectType(final ChoiceNode objectType, final ChoiceNode addressFamily) {
+        return new TeLspCaseBuilder()
+            .setLspId(new LspId((Uint32) objectType.getChildByArg(LSP_ID).body()))
+            .setTunnelId(new TunnelId((Uint16) objectType.getChildByArg(TUNNEL_ID).body()))
+            .setAddressFamily(serializeAddressFamily(addressFamily,
+                addressFamily.childByArg(IPV4_TUNNEL_SENDER_ADDRESS) != null))
             .build();
     }
 
index 9dfcbc99390ef823e774355c07112af9c288b6e2..3d0efe246582a34ce5854ad872b6e0e4d9fb44c3 100644 (file)
@@ -8,8 +8,6 @@
 
 package org.opendaylight.protocol.bgp.route.targetcontrain.impl.route.policy;
 
-import java.util.List;
-import java.util.Optional;
 import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.RouteEntryBaseAttributes;
 import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.policy.action.BgpActionAugPolicy;
 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryExportParameters;
@@ -22,7 +20,7 @@ public final class ClientAttributePrependHandler implements BgpActionAugPolicy<C
     private static final ClientAttributePrependHandler INSTANCE = new ClientAttributePrependHandler();
 
     private ClientAttributePrependHandler() {
-
+        // Hidden on purpose
     }
 
     public static ClientAttributePrependHandler getInstance() {
@@ -37,19 +35,15 @@ public final class ClientAttributePrependHandler implements BgpActionAugPolicy<C
         return attributes;
     }
 
-
     @Override
     public Attributes applyExportAction(final RouteEntryBaseAttributes routeEntryInfo,
             final BGPRouteEntryExportParameters exportParameters,
             final Attributes attributes,
             final ClientAttributePrepend actions) {
-        final List<Route> rtRoutes = exportParameters.getClientRouteTargetContrainCache();
-        final Optional<Route> found = rtRoutes.stream()
-                .filter(rt -> rt.getRouteKey().equals(exportParameters.getRouteKey()))
-                .findFirst();
-        if (found.isPresent()) {
-            return found.get().getAttributes();
-        }
-        return attributes;
+        return exportParameters.getClientRouteTargetContrainCache().stream()
+            .filter(rt -> rt.getRouteKey().equals(exportParameters.getRouteKey()))
+            .findFirst()
+            .map(Route::getAttributes)
+            .orElse(attributes);
     }
 }
\ No newline at end of file
index f1a0d9f14a51ac66d84cc978dcda81896105c825..55efb71c9ea8d4f93e76196dbdea084161b54aff 100644 (file)
@@ -89,10 +89,7 @@ final class BGPRibPolicyImpl implements BGPRibRoutingPolicy {
         final Optional<Statements> result =
                 tr.read(LogicalDatastoreType.CONFIGURATION, ROUTING_POLICY_IID.child(PolicyDefinitions.class)
                         .child(PolicyDefinition.class, new PolicyDefinitionKey(key)).child(Statements.class)).get();
-        if (!result.isPresent()) {
-            return List.of();
-        }
-        return result.get().getStatement();
+        return result.map(Statements::getStatement).orElse(List.of());
     }
 
     @Override
index deaa7cea90000f81124313c2975c1afd45871056..d6666015c770a169b5f20cf721e7bc1187890fdb 100644 (file)
@@ -124,7 +124,7 @@ public final class BGPOpenMessageParser implements MessageParser, MessageSeriali
         for (final BgpParameters param : params) {
             final Optional<ParameterSerializer> optSer = reg.findSerializer(param);
             if (optSer.isPresent()) {
-                optSer.get().serializeExtendedParameter(param, buffer);
+                optSer.orElseThrow().serializeExtendedParameter(param, buffer);
             } else {
                 LOG.debug("Ignoring unregistered parameter {}", param);
             }
@@ -149,7 +149,7 @@ public final class BGPOpenMessageParser implements MessageParser, MessageSeriali
             final Optional<ParameterSerializer> optSer = reg.findSerializer(param);
             if (optSer.isPresent()) {
                 try {
-                    optSer.get().serializeParameter(param, buffer);
+                    optSer.orElseThrow().serializeParameter(param, buffer);
                 } catch (ParameterLengthOverflowException e) {
                     LOG.debug("Forcing extended parameter serialization", e);
                     return null;
@@ -251,7 +251,7 @@ public final class BGPOpenMessageParser implements MessageParser, MessageSeriali
 
             final BgpParameters param;
             try {
-                param = parser.get().parseParameter(paramBody);
+                param = parser.orElseThrow().parseParameter(paramBody);
             } catch (final BGPParsingException e) {
                 throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR, e);
             }
index 30bc448e253f6c5fb7a7151a9442fc882925afdc..9e4e69941f8957166f8e7d331b71c874396a6afc 100644 (file)
@@ -177,7 +177,7 @@ public final class BGPUpdateMessageParser implements MessageParser, MessageSeria
         } catch (BGPTreatAsWithdrawException e) {
             LOG.debug("Well-known mandatory attributes missing", e);
             if (withdrawCauseOpt.isPresent()) {
-                final BGPTreatAsWithdrawException exception = withdrawCauseOpt.get();
+                final BGPTreatAsWithdrawException exception = withdrawCauseOpt.orElseThrow();
                 exception.addSuppressed(e);
                 withdrawCauseOpt = Optional.of(exception);
             } else {
@@ -188,7 +188,7 @@ public final class BGPUpdateMessageParser implements MessageParser, MessageSeria
         Update msg = builder.build();
         if (withdrawCauseOpt.isPresent()) {
             // Attempt to apply treat-as-withdraw
-            msg = withdrawUpdate(msg, errorHandling, withdrawCauseOpt.get());
+            msg = withdrawUpdate(msg, errorHandling, withdrawCauseOpt.orElseThrow());
         }
 
         LOG.debug("BGP Update message was parsed {}.", msg);
index eb2d72da0ea2a1fbdfb63fa32a1230e3d76ad739..e9f10fd67d6081c916cfe622ec895a1bf75ad70a 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.protocol.bgp.parser.spi;
 
 import static java.util.Objects.requireNonNull;
 
-import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
@@ -29,8 +28,8 @@ public final class MultiPathSupportUtil {
             final @NonNull BgpTableType afiSafi) {
         requireNonNull(afiSafi);
         if (constraints != null) {
-            final Optional<MultiPathSupport> peerConstraint = constraints.getPeerConstraint(MultiPathSupport.class);
-            return peerConstraint.isPresent() && peerConstraint.get().isTableTypeSupported(afiSafi);
+            final var peerConstraint = constraints.getPeerConstraint(MultiPathSupport.class);
+            return peerConstraint.isPresent() && peerConstraint.orElseThrow().isTableTypeSupported(afiSafi);
         }
         return false;
     }
index b560d5af6d5d44babc0baf63a2aa1f431ab7e24e..b3b6bc1688cfad041dafcbedf2f5de87187db19d 100644 (file)
@@ -94,7 +94,7 @@ public final class PathIdUtil {
             final ImmutableOffsetMapTemplate<QName> routeKeyTemplate, final Object routeKeyValue,
             final Optional<DataContainerChild> maybePathIdLeaf) {
         // FIXME: a cache here would mean we instantiate the same identifier for each route making comparison quicker.
-        final Object pathId = maybePathIdLeaf.isPresent() ? maybePathIdLeaf.get().body() : NON_PATH_ID_VALUE;
+        final Object pathId = maybePathIdLeaf.map(DataContainerChild::body).orElse(NON_PATH_ID_VALUE);
         return NodeIdentifierWithPredicates.of(routeQName,
             routeKeyTemplate.instantiateWithValues(pathId, routeKeyValue));
     }
index c3328f5fe806115cbed20150fd45dcaf09b3c7ed..a0526ebf0eb7707731fbcb15129c0eb33df1d6ea 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.protocol.bgp.mode.impl;
 
-import static com.google.common.base.Verify.verifyNotNull;
 import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.MoreObjects;
@@ -115,14 +114,14 @@ public final class BestPathStateImpl implements BestPathState {
 
         final Optional<NormalizedNode> maybeMultiExitDisc = NormalizedNodes.findNode(attributes, ids.med);
         if (maybeMultiExitDisc.isPresent()) {
-            multiExitDisc = ((Uint32) maybeMultiExitDisc.get().body()).toJava();
+            multiExitDisc = ((Uint32) maybeMultiExitDisc.orElseThrow().body()).toJava();
         } else {
             multiExitDisc = 0L;
         }
 
         final Optional<NormalizedNode> maybeOrigin = NormalizedNodes.findNode(attributes, ids.orig);
         if (maybeOrigin.isPresent()) {
-            final String originStr = (String) maybeOrigin.get().body();
+            final String originStr = (String) maybeOrigin.orElseThrow().body();
             origin = BgpOrigin.forName(originStr);
             if (origin == null) {
                 throw new IllegalArgumentException("Unhandled origin value " + originStr);
@@ -133,7 +132,7 @@ public final class BestPathStateImpl implements BestPathState {
 
         final Optional<NormalizedNode> maybeSegments = NormalizedNodes.findNode(attributes, ids.asPath);
         if (maybeSegments.isPresent()) {
-            final UnkeyedListNode segments = (UnkeyedListNode) maybeSegments.get();
+            final UnkeyedListNode segments = (UnkeyedListNode) maybeSegments.orElseThrow();
             final List<Segments> segs = extractSegments(segments, ids);
             if (!segs.isEmpty()) {
                 peerAs = BesthPathStateUtil.getPeerAs(segs);
@@ -153,8 +152,8 @@ public final class BestPathStateImpl implements BestPathState {
     }
 
     private static boolean isStale(final NamespaceSpecificIds ids, final UnkeyedListEntryNode community) {
-        return LLGR_STALE_AS_NUMBER.equals(verifyNotNull(community.childByArg(ids.asNumber)).body())
-            && LLGR_STALE_SEMANTICS.equals(verifyNotNull(community.childByArg(ids.semantics)).body());
+        return LLGR_STALE_AS_NUMBER.equals(community.getChildByArg(ids.asNumber).body())
+            && LLGR_STALE_SEMANTICS.equals(community.getChildByArg(ids.semantics).body());
     }
 
     @Override
@@ -266,7 +265,7 @@ public final class BestPathStateImpl implements BestPathState {
             final UnkeyedListEntryNode segment, final NodeIdentifier nid) {
         final Optional<NormalizedNode> maybeAsList = NormalizedNodes.findNode(segment, nid);
         if (maybeAsList.isPresent()) {
-            final LeafSetNode<?> list = (LeafSetNode<?>)maybeAsList.get();
+            final LeafSetNode<?> list = (LeafSetNode<?>)maybeAsList.orElseThrow();
             for (final LeafSetEntryNode<?> as : list.body())  {
                 ases.add(new AsNumber((Uint32) as.body()));
             }
index 5ef287f1aa58b51a9723b8add27ad5df6886b9db..e060c42163f889eb9084d299b5fdd18d51426c77 100644 (file)
@@ -341,7 +341,7 @@ abstract class AbstractPeer extends BGPPeerStateImpl implements BGPRouteEntryImp
                 final Optional<ContainerNode> effAttr = applyExportPolicy(entryDep, fromPeerId, route, routePath,
                     actualBestRoute.getAttributes());
                 if (effAttr.isPresent()) {
-                    storeRoute(ribSupport, actualBestRoute, route, routePath, effAttr.get(), tx);
+                    storeRoute(ribSupport, actualBestRoute, route, routePath, effAttr.orElseThrow(), tx);
                     continue;
                 }
             }
index eb96e2d0895dfc6066fd6302890917abbc61220c..c070d361807797d0ca409d9f667dfe7e6d7626be 100644 (file)
@@ -352,7 +352,7 @@ final class AdjRibInWriter {
                             try {
                                 if (routesOptional.isPresent()) {
                                     synchronized (staleRoutesRegistry) {
-                                        final MapNode routesNode = (MapNode) routesOptional.get();
+                                        final MapNode routesNode = (MapNode) routesOptional.orElseThrow();
                                         final List<NodeIdentifierWithPredicates> routes = routesNode.body().stream()
                                                 .map(MapEntryNode::getIdentifier)
                                                 .collect(Collectors.toList());
index 7b28d91e209b342a3b0b0f3f1aabeda88e7d3d79..05443bf1eabf5fd3edcc87b1e10793a73e5d0792 100644 (file)
@@ -137,13 +137,13 @@ final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener, Pre
             case DELETE:
             case DISAPPEARED:
                 // FIXME: we can batch deletions into a single batch
-                update = withdraw((MapEntryNode) route.getDataBefore().get());
+                update = withdraw((MapEntryNode) route.getDataBefore().orElseThrow());
                 LOG.debug("Withdrawing routes {}", update);
                 break;
             case APPEARED:
             case SUBTREE_MODIFIED:
             case WRITE:
-                update = advertise((MapEntryNode) route.getDataAfter().get());
+                update = advertise((MapEntryNode) route.getDataAfter().orElseThrow());
                 LOG.debug("Advertising routes {}", update);
                 break;
             default:
index 27d1530c476e17af68d783a5ba73f38894110d2a..eadd7ec788f1a040b78461c9aa91ea239f5f87fe 100644 (file)
@@ -57,7 +57,6 @@ import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
 import org.slf4j.Logger;
@@ -234,12 +233,11 @@ public class ApplicationPeer extends AbstractPeer implements ClusteredDOMDataTre
 
     private static void processWrite(final DataTreeCandidateNode child, final YangInstanceIdentifier tableId,
             final DOMDataTreeWriteTransaction tx) {
-        if (child.getDataAfter().isPresent()) {
-            final NormalizedNode dataAfter = child.getDataAfter().get();
+        child.getDataAfter().ifPresent(dataAfter -> {
             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
-        }
+        });
     }
 
     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
@@ -275,12 +273,11 @@ public class ApplicationPeer extends AbstractPeer implements ClusteredDOMDataTre
 
     private static void processRouteWrite(final DataTreeCandidateNode child,
             final YangInstanceIdentifier childIdentifier, final DOMDataTreeWriteTransaction tx) {
-        if (child.getDataAfter().isPresent()) {
-            final NormalizedNode dataAfter = child.getDataAfter().get();
+        child.getDataAfter().ifPresent(dataAfter -> {
             LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
             tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
-        }
+        });
     }
 
     @Override
index 9483f85b414e836c1e4917b19ac73189b480f360..858de61cce58f879ca5ce845624c7259a31bc4a5 100644 (file)
@@ -481,7 +481,7 @@ public class BGPPeer extends AbstractPeer implements BGPSessionListener {
         // SpotBugs does not grok Optional.ifPresent() and thinks we are using unsynchronized access
         final Optional<RevisedErrorHandlingSupport> errorHandling = bgpPeer.getErrorHandling();
         if (errorHandling.isPresent()) {
-            currentSession.addDecoderConstraint(RevisedErrorHandlingSupport.class, errorHandling.get());
+            currentSession.addDecoderConstraint(RevisedErrorHandlingSupport.class, errorHandling.orElseThrow());
         }
     }
 
index 44b7192150c0bbfc55a409ec19052aa52432b69a..f2404152c327fe07ef95ebc2fa3aa4e6039e6903 100644 (file)
@@ -335,8 +335,8 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
             final YangInstanceIdentifier effAttrsPath = effectiveTablePath.node(ATTRIBUTES_NID);
             final Optional<NormalizedNode> optAttrsAfter = modifiedAttrs.getDataAfter();
             if (optAttrsAfter.isPresent()) {
-                tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath, effectiveAttributes(
-                    NormalizedNodes.findNode(optAttrsAfter.get(), UPTODATE_NID)));
+                tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath,
+                    effectiveAttributes(extractContainer(optAttrsAfter.orElseThrow())));
             } else {
                 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
             }
@@ -379,16 +379,18 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
 
         final Optional<NormalizedNode> maybeTableAfter = table.getDataAfter();
         if (maybeTableAfter.isPresent()) {
-            final MapEntryNode tableAfter = extractMapEntry(maybeTableAfter);
+            final NormalizedNode node = maybeTableAfter.orElseThrow();
+            verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
+            final MapEntryNode tableAfter = (MapEntryNode) node;
             ribContext.createEmptyTableStructure(tx, effectiveTablePath);
 
-            final Optional<DataContainerChild> maybeAttrsAfter = tableAfter.findChildByArg(ATTRIBUTES_NID);
+            final DataContainerChild maybeAttrsAfter = tableAfter.childByArg(ATTRIBUTES_NID);
             final boolean longLivedStale;
-            if (maybeAttrsAfter.isPresent()) {
+            if (maybeAttrsAfter != null) {
                 final ContainerNode attrsAfter = extractContainer(maybeAttrsAfter);
                 longLivedStale = isLongLivedStale(attrsAfter);
                 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ATTRIBUTES_NID),
-                    effectiveAttributes(attrsAfter.findChildByArg(UPTODATE_NID)));
+                    effectiveAttributes(attrsAfter));
             } else {
                 longLivedStale = false;
             }
@@ -461,7 +463,7 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
             case APPEARED:
             case SUBTREE_MODIFIED:
             case WRITE:
-                writeRoute(tx, ribSupport, routePath, route.getDataBefore(), route.getDataAfter().get(),
+                writeRoute(tx, ribSupport, routePath, route.getDataBefore(), route.getDataAfter().orElseThrow(),
                     longLivedStale);
                 break;
             default:
@@ -503,7 +505,7 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
             optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
                 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
         }
-        if (!optEffAtt.isPresent()) {
+        if (optEffAtt.isEmpty()) {
             deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
             return;
         }
@@ -511,7 +513,7 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
         tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
         CountersUtil.increment(prefixesInstalled.get(tablesKey), tablesKey);
 
-        final Attributes attToStore = optEffAtt.get();
+        final Attributes attToStore = optEffAtt.orElseThrow();
         if (!attToStore.equals(routeAttrs)) {
             final YangInstanceIdentifier attPath = routePath.node(ribSupport.routeAttributesIdentifier());
             final ContainerNode finalAttribute = ribSupport.attributeToContainerNode(attPath, attToStore);
@@ -597,39 +599,35 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
         return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
     }
 
-    private static ContainerNode extractContainer(final Optional<? extends NormalizedNode> optNode) {
-        final NormalizedNode node = optNode.get();
+    private static ContainerNode extractContainer(final NormalizedNode node) {
         verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
         return (ContainerNode) node;
     }
 
     private static MapNode extractMap(final Optional<? extends NormalizedNode> optNode) {
-        final NormalizedNode node = optNode.get();
+        final NormalizedNode node = optNode.orElseThrow();
         verify(node instanceof MapNode, "Expected MapNode, got %s", node);
         return (MapNode) node;
     }
 
-    private static MapEntryNode extractMapEntry(final Optional<? extends NormalizedNode> optNode) {
-        final NormalizedNode node = optNode.get();
-        verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
-        return (MapEntryNode) node;
-    }
-
     private static boolean isLongLivedStale(final ContainerNode attributes) {
         return NormalizedNodes.findNode(attributes, ADJRIBIN_ATTRIBUTES_AID, LLGR_STALE_NID).isPresent();
     }
 
     private static boolean isLongLivedStaleTable(final Optional<NormalizedNode> optTable) {
         final Optional<NormalizedNode> optAttributes = NormalizedNodes.findNode(optTable, ATTRIBUTES_NID);
-        return optAttributes.isPresent() && isLongLivedStale(extractContainer(optAttributes));
+        return optAttributes.isPresent() && isLongLivedStale(extractContainer(optAttributes.orElseThrow()));
     }
 
-    private static ContainerNode effectiveAttributes(final Optional<? extends NormalizedNode> optUptodate) {
-        return optUptodate.map(leaf -> {
-            final Object value = leaf.body();
+    private static ContainerNode effectiveAttributes(final ContainerNode attrs) {
+        final var upToDate = attrs.childByArg(UPTODATE_NID);
+        if (upToDate != null) {
+            final Object value = upToDate.body();
             verify(value instanceof Boolean, "Expected boolean uptodate, got %s", value);
-            return (Boolean) value ? RIBNormalizedNodes.UPTODATE_ATTRIBUTES
-                    : RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
-        }).orElse(RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES);
+            if ((Boolean) value) {
+                return RIBNormalizedNodes.UPTODATE_ATTRIBUTES;
+            }
+        }
+        return RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
     }
 }
index 170e1b955519a39596030f338e2cc3db4056cd5f..95698bbb50f6dcf5dc6de5b625e14a3cdebe9355 100644 (file)
@@ -109,15 +109,15 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
         this.ribIId = requireNonNull(ribIId);
         this.ribSupport = requireNonNull(ribSupport);
 
-        this.locRibTableIID = ribIId.node(LOCRIB_NID).node(TABLES_NID).node(ribSupport.emptyTable().getIdentifier())
+        locRibTableIID = ribIId.node(LOCRIB_NID).node(TABLES_NID).node(ribSupport.emptyTable().getIdentifier())
             .toOptimized();
         this.ourAs = ourAs.toJava();
         this.dataBroker = requireNonNull(dataBroker);
         this.peerTracker = peerTracker;
         this.pathSelectionMode = pathSelectionMode;
 
-        this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
-                afiSafiType, this.locRibTableIID);
+        entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
+                afiSafiType, locRibTableIID);
     }
 
     public static <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>>
@@ -138,8 +138,8 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
     }
 
     private synchronized void init() {
-        final DOMDataTreeWriteTransaction tx = this.chain.newWriteOnlyTransaction();
-        tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.node(ATTRIBUTES_NID).node(UPTODATE_NID),
+        final DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
+        tx.put(LogicalDatastoreType.OPERATIONAL, locRibTableIID.node(ATTRIBUTES_NID).node(UPTODATE_NID),
                 RIBNormalizedNodes.ATTRIBUTES_UPTODATE_TRUE);
         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
             @Override
@@ -153,7 +153,7 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
             }
         }, MoreExecutors.directExecutor());
 
-        this.reg = this.dataBroker.registerDataTreeChangeListener(new DOMDataTreeIdentifier(
+        reg = dataBroker.registerDataTreeChangeListener(new DOMDataTreeIdentifier(
             LogicalDatastoreType.OPERATIONAL, ribIId.node(PEER_NID).node(PEER_NID).node(EFFRIBIN_NID).node(TABLES_NID)
                 .node(locRibTableIID.getLastPathArgument())), this);
     }
@@ -166,26 +166,26 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
     synchronized void restart(final @NonNull DOMTransactionChain newChain) {
         requireNonNull(newChain);
         close();
-        this.chain = newChain;
+        chain = newChain;
         init();
     }
 
     @Override
     public synchronized void close() {
-        if (this.reg != null) {
-            this.reg.close();
-            this.reg = null;
+        if (reg != null) {
+            reg.close();
+            reg = null;
         }
-        if (this.chain != null) {
-            this.chain.close();
-            this.chain = null;
+        if (chain != null) {
+            chain.close();
+            chain = null;
         }
     }
 
     private @NonNull RouteEntry<C, S> createEntry(final String routeId) {
-        final RouteEntry<C, S> ret = this.pathSelectionMode.createRouteEntry();
-        this.routeEntries.put(routeId, ret);
-        this.totalPrefixesCounter.increment();
+        final RouteEntry<C, S> ret = pathSelectionMode.createRouteEntry();
+        routeEntries.put(routeId, ret);
+        totalPrefixesCounter.increment();
         LOG.trace("Created new entry for {}", routeId);
         return ret;
     }
@@ -204,12 +204,12 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
     @Override
     @SuppressWarnings("checkstyle:illegalCatch")
     public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
-        if (this.chain == null) {
+        if (chain == null) {
             LOG.trace("Chain closed, ignoring received data change {} to LocRib {}", changes, this);
             return;
         }
         LOG.trace("Received data change {} to LocRib {}", changes, this);
-        final DOMDataTreeWriteTransaction tx = this.chain.newWriteOnlyTransaction();
+        final DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
         try {
             final Map<RouteUpdateKey, RouteEntry<C, S>> toUpdate = update(tx, changes);
 
@@ -244,18 +244,18 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
             /*
             Initialize Peer with routes under loc rib
              */
-            if (!this.routeEntries.isEmpty() && table.getDataBefore().isEmpty()) {
+            if (!routeEntries.isEmpty() && table.getDataBefore().isEmpty()) {
                 final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer
-                        = this.peerTracker.getPeer(peerUuid.getPeerId());
-                if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
+                        = peerTracker.getPeer(peerUuid.getPeerId());
+                if (toPeer != null && toPeer.supportsTable(entryDep.getLocalTablesKey())) {
                     LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
                     final List<ActualBestPathRoutes<C, S>> routesToStore = new ArrayList<>();
-                    for (final Entry<String, RouteEntry<C, S>> entry : this.routeEntries.entrySet()) {
+                    for (final Entry<String, RouteEntry<C, S>> entry : routeEntries.entrySet()) {
                         final List<ActualBestPathRoutes<C, S>> filteredRoute = entry.getValue()
-                                .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
+                                .actualBestPaths(ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
                         routesToStore.addAll(filteredRoute);
                     }
-                    toPeer.initializeRibOut(this.entryDep, routesToStore);
+                    toPeer.initializeRibOut(entryDep, routesToStore);
                 }
             }
             /*
@@ -270,7 +270,7 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
             final DOMDataTreeWriteOperations tx, final Map<RouteUpdateKey, RouteEntry<C, S>> routes) {
         table.getModifiedChild(ATTRIBUTES_NID).flatMap(DataTreeCandidateNode::getDataAfter).ifPresent(newAttValue -> {
             LOG.trace("Uptodate found for {}", newAttValue);
-            tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.node(ATTRIBUTES_NID), newAttValue);
+            tx.put(LogicalDatastoreType.OPERATIONAL, locRibTableIID.node(ATTRIBUTES_NID), newAttValue);
         });
 
         table.getModifiedChild(ROUTES_NID).ifPresent(modifiedRoutes -> {
@@ -293,27 +293,27 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
             RouteEntry<C, S> entry;
             switch (route.getModificationType()) {
                 case DELETE:
-                    entry = this.routeEntries.get(routeKey);
+                    entry = routeEntries.get(routeKey);
                     if (entry != null) {
-                        this.totalPathsCounter.decrement();
+                        totalPathsCounter.decrement();
                         if (entry.removeRoute(routerId, pathId)) {
-                            this.routeEntries.remove(routeKey);
-                            this.totalPrefixesCounter.decrement();
+                            routeEntries.remove(routeKey);
+                            totalPrefixesCounter.decrement();
                             LOG.trace("Removed route from {}", routerId);
                         }
                     }
                     break;
                 case SUBTREE_MODIFIED:
                 case WRITE:
-                    entry = this.routeEntries.get(routeKey);
+                    entry = routeEntries.get(routeKey);
                     if (entry == null) {
                         entry = createEntry(routeKey);
                     }
 
-                    final NormalizedNode routeAfter = route.getDataAfter().get();
+                    final NormalizedNode routeAfter = route.getDataAfter().orElseThrow();
                     verify(routeAfter instanceof MapEntryNode, "Unexpected route %s", routeAfter);
                     entry.addRoute(routerId, pathId, (MapEntryNode) routeAfter);
-                    this.totalPathsCounter.increment();
+                    totalPathsCounter.increment();
                     break;
                 default:
                     throw new IllegalStateException("Unhandled route modification " + route);
@@ -333,23 +333,23 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
             LOG.trace("Walking through {}", e);
             final RouteEntry<C, S> entry = e.getValue();
 
-            if (!entry.selectBest(this.ribSupport, this.ourAs)) {
+            if (!entry.selectBest(ribSupport, ourAs)) {
                 LOG.trace("Best path has not changed, continuing");
                 continue;
             }
 
-            entry.removeStalePaths(this.ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
-            newRoutes.addAll(entry.newBestPaths(this.ribSupport, e.getKey().getRouteId()));
+            entry.removeStalePaths(ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
+            newRoutes.addAll(entry.newBestPaths(ribSupport, e.getKey().getRouteId()));
         }
         updateLocRib(newRoutes, staleRoutes, tx);
-        this.peerTracker.getNonInternalPeers().parallelStream()
-                .filter(toPeer -> toPeer.supportsTable(this.entryDep.getLocalTablesKey()))
-                .forEach(toPeer -> toPeer.refreshRibOut(this.entryDep, staleRoutes, newRoutes));
+        peerTracker.getNonInternalPeers().parallelStream()
+                .filter(toPeer -> toPeer.supportsTable(entryDep.getLocalTablesKey()))
+                .forEach(toPeer -> toPeer.refreshRibOut(entryDep, staleRoutes, newRoutes));
     }
 
     private void updateLocRib(final List<AdvertizedRoute<C, S>> newRoutes, final List<StaleBestPathRoute> staleRoutes,
             final DOMDataTreeWriteOperations tx) {
-        final YangInstanceIdentifier locRibTarget = this.entryDep.getLocRibTableTarget();
+        final YangInstanceIdentifier locRibTarget = entryDep.getLocRibTableTarget();
 
         for (final StaleBestPathRoute staleContainer : staleRoutes) {
             for (final NodeIdentifierWithPredicates routeId : staleContainer.getStaleRouteKeyIdentifiers()) {
@@ -362,7 +362,7 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
         for (final AdvertizedRoute<C, S> advRoute : newRoutes) {
             final MapEntryNode route = advRoute.getRoute();
             final NodeIdentifierWithPredicates iid = advRoute.getAddPathRouteKeyIdentifier();
-            final YangInstanceIdentifier locRibRouteTarget = this.ribSupport.createRouteIdentifier(locRibTarget, iid);
+            final YangInstanceIdentifier locRibRouteTarget = ribSupport.createRouteIdentifier(locRibTarget, iid);
             LOG.debug("Write LocRib route {}", locRibRouteTarget);
             if (LOG.isTraceEnabled()) {
                 LOG.trace("Write route to LocRib {}", NormalizedNodes.toStringTree(route));
@@ -373,30 +373,30 @@ final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S ext
 
     @Override
     public long getPrefixesCount() {
-        return this.totalPrefixesCounter.longValue();
+        return totalPrefixesCounter.longValue();
     }
 
     @Override
     public long getPathsCount() {
-        return this.totalPathsCounter.longValue();
+        return totalPathsCounter.longValue();
     }
 
     TablesKey getTableKey() {
-        return this.ribSupport.getTablesKey();
+        return ribSupport.getTablesKey();
     }
 
     @Override
     public synchronized void refreshTable(final TablesKey tk, final PeerId peerId) {
-        final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer = this.peerTracker.getPeer(peerId);
-        if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
+        final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer = peerTracker.getPeer(peerId);
+        if (toPeer != null && toPeer.supportsTable(entryDep.getLocalTablesKey())) {
             LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
             final List<ActualBestPathRoutes<C, S>> routesToStore = new ArrayList<>();
-            for (final Entry<String, RouteEntry<C, S>> entry : this.routeEntries.entrySet()) {
+            for (final Entry<String, RouteEntry<C, S>> entry : routeEntries.entrySet()) {
                 final List<ActualBestPathRoutes<C, S>> filteredRoute = entry.getValue()
-                        .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
+                        .actualBestPaths(ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
                 routesToStore.addAll(filteredRoute);
             }
-            toPeer.reEvaluateAdvertizement(this.entryDep, routesToStore);
+            toPeer.reEvaluateAdvertizement(entryDep, routesToStore);
         }
     }
 }
index e0576a9e1e22c0a4c298c632251b61e74445bd3d..69a2e58a9a42d3d4a6f205e8a402acec012aa68a 100644 (file)
@@ -157,35 +157,35 @@ public abstract class AbstractRIBSupport<
             final SubsequentAddressFamily safiClass,
             final QName destContainerQname) {
         final QNameModule module = BindingReflections.getQNameModule(cazeClass);
-        this.routesContainerIdentifier = NodeIdentifier.create(
+        routesContainerIdentifier = NodeIdentifier.create(
             BindingReflections.findQName(containerClass).bindTo(module));
-        this.routeAttributesIdentifier = NodeIdentifier.create(Attributes.QNAME.bindTo(module));
+        routeAttributesIdentifier = NodeIdentifier.create(Attributes.QNAME.bindTo(module));
         this.cazeClass = requireNonNull(cazeClass);
         this.mappingService = requireNonNull(mappingService);
         this.containerClass = requireNonNull(containerClass);
         this.listClass = requireNonNull(listClass);
-        this.routeQname = BindingReflections.findQName(listClass).bindTo(module);
-        this.routeKeyQname = QName.create(module, ROUTE_KEY).intern();
-        this.routesListIdentifier = NodeIdentifier.create(routeQname);
+        routeQname = BindingReflections.findQName(listClass).bindTo(module);
+        routeKeyQname = QName.create(module, ROUTE_KEY).intern();
+        routesListIdentifier = NodeIdentifier.create(routeQname);
         this.afiClass = requireNonNull(afiClass);
         this.safiClass = requireNonNull(safiClass);
-        this.tk = new TablesKey(afiClass, safiClass);
-        this.tablesKey = NodeIdentifierWithPredicates.of(Tables.QNAME, TABLES_KEY_TEMPLATE.instantiateWithValues(
+        tk = new TablesKey(afiClass, safiClass);
+        tablesKey = NodeIdentifierWithPredicates.of(Tables.QNAME, TABLES_KEY_TEMPLATE.instantiateWithValues(
             BindingReflections.findQName(afiClass.implementedInterface()),
             BindingReflections.findQName(safiClass.implementedInterface())));
 
-        this.emptyTable = (MapEntryNode) this.mappingService
+        emptyTable = (MapEntryNode) this.mappingService
                 .toNormalizedNode(TABLES_II, new TablesBuilder().withKey(tk)
                         .setAttributes(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
                                 .rev180329.rib.tables.AttributesBuilder().build()).build()).getValue();
-        this.destinationNid = NodeIdentifier.create(destContainerQname);
-        this.pathIdNid = NodeIdentifier.create(QName.create(routeQName(), "path-id").intern());
-        this.prefixTypeNid = NodeIdentifier.create(QName.create(destContainerQname, "prefix").intern());
-        this.rdNid = NodeIdentifier.create(QName.create(destContainerQname, "route-distinguisher").intern());
-        this.routeDefaultYii = YangInstanceIdentifier.create(BGPRIB_NID, RIB_NID, RIB_NID, LOCRIB_NID,
+        destinationNid = NodeIdentifier.create(destContainerQname);
+        pathIdNid = NodeIdentifier.create(QName.create(routeQName(), "path-id").intern());
+        prefixTypeNid = NodeIdentifier.create(QName.create(destContainerQname, "prefix").intern());
+        rdNid = NodeIdentifier.create(QName.create(destContainerQname, "route-distinguisher").intern());
+        routeDefaultYii = YangInstanceIdentifier.create(BGPRIB_NID, RIB_NID, RIB_NID, LOCRIB_NID,
             TABLES_NID, TABLES_NID, ROUTES_NID, routesContainerIdentifier, routesListIdentifier, routesListIdentifier);
-        this.relativeRoutesPath = ImmutableList.of(routesContainerIdentifier, routesListIdentifier);
-        this.routeKeyTemplate = ImmutableOffsetMapTemplate.ordered(
+        relativeRoutesPath = ImmutableList.of(routesContainerIdentifier, routesListIdentifier);
+        routeKeyTemplate = ImmutableOffsetMapTemplate.ordered(
             ImmutableList.of(pathIdNid.getNodeType(), routeKeyQname));
     }
 
@@ -284,7 +284,7 @@ public abstract class AbstractRIBSupport<
      * @return Container identifier, may not be null.
      */
     public final NodeIdentifier routesContainerIdentifier() {
-        return this.routesContainerIdentifier;
+        return routesContainerIdentifier;
     }
 
     /**
@@ -294,7 +294,7 @@ public abstract class AbstractRIBSupport<
      * @return Container identifier, may not be null.
      */
     private NodeIdentifier destinationContainerIdentifier() {
-        return this.destinationNid;
+        return destinationNid;
     }
 
     /**
@@ -331,7 +331,7 @@ public abstract class AbstractRIBSupport<
     private Collection<NodeIdentifierWithPredicates> putDestinationRoutes(final DOMDataTreeWriteTransaction tx,
             final YangInstanceIdentifier tablePath, final ContainerNode destination, final ContainerNode attributes,
             final NodeIdentifier routesNodeId) {
-        return processDestination(tx, tablePath.node(routesNodeId), destination, attributes, this.putRoute);
+        return processDestination(tx, tablePath.node(routesNodeId), destination, attributes, putRoute);
     }
 
     protected abstract Collection<NodeIdentifierWithPredicates> processDestination(DOMDataTreeWriteTransaction tx,
@@ -364,12 +364,12 @@ public abstract class AbstractRIBSupport<
 
     @Override
     public final NodeIdentifier routeAttributesIdentifier() {
-        return this.routeAttributesIdentifier;
+        return routeAttributesIdentifier;
     }
 
     @Override
     public final Collection<DataTreeCandidateNode> changedRoutes(final DataTreeCandidateNode routes) {
-        return routes.getModifiedChild(this.routesContainerIdentifier)
+        return routes.getModifiedChild(routesContainerIdentifier)
             .flatMap(myRoutes -> myRoutes.getModifiedChild(routeNid()))
             // Well, given the remote possibility of augmentation, we should perform a filter here,
             // to make sure the type matches what routeType() reports.
@@ -528,7 +528,7 @@ public abstract class AbstractRIBSupport<
     }
 
     protected final String extractPrefix(final DataContainerNode route) {
-        return (String) verifyNotNull(route.childByArg(prefixTypeNid)).body();
+        return (String) route.getChildByArg(prefixTypeNid).body();
     }
 
     protected final RouteDistinguisher extractRouteDistinguisher(final DataContainerNode route) {
@@ -549,13 +549,13 @@ public abstract class AbstractRIBSupport<
 
     @Override
     public Attributes attributeFromContainerNode(final ContainerNode advertisedAttrs) {
-        final YangInstanceIdentifier path = this.routeDefaultYii.node(routeAttributesIdentifier());
+        final YangInstanceIdentifier path = routeDefaultYii.node(routeAttributesIdentifier());
         return (Attributes) verifyNotNull(mappingService.fromNormalizedNode(path, advertisedAttrs).getValue());
     }
 
     @Override
     public ContainerNode attributeToContainerNode(final YangInstanceIdentifier attPath, final Attributes attributes) {
-        final InstanceIdentifier<DataObject> iid = this.mappingService.fromYangInstanceIdentifier(attPath);
+        final InstanceIdentifier<DataObject> iid = mappingService.fromYangInstanceIdentifier(attPath);
         return (ContainerNode) verifyNotNull(mappingService.toNormalizedNode(iid, attributes).getValue());
     }
 
index 79d1f8407a6c4d8a6915c41030fc900fc5af2bba..71f5a25c0923efbb6f847e86ce0c617730208804 100644 (file)
@@ -32,7 +32,7 @@ public final class IdentifierUtils {
     // FIXME: implement as id.firstIdentifierOf(IS_PEER), null indicating not found
     private static NodeIdentifierWithPredicates firstKeyOf(final YangInstanceIdentifier id,
             final Predicate<PathArgument> match) {
-        final PathArgument ret = id.getPathArguments().stream().filter(match::apply).findFirst().get();
+        final PathArgument ret = id.getPathArguments().stream().filter(match::apply).findFirst().orElseThrow();
         Preconditions.checkArgument(ret instanceof NodeIdentifierWithPredicates,
                 "Non-key peer identifier %s", ret);
         return (NodeIdentifierWithPredicates) ret;
index 0b489505ff293f4870fa182a20900cf8c6e80523..76dfd38fca39c7213121cf0bcf101a50607db8c8 100644 (file)
@@ -97,7 +97,7 @@ public final class BmpRouterImpl implements BmpRouter, DOMTransactionChainListen
         if (!sessionManager.addSessionListener(this)) {
             LOG.warn("Redundant BMP session with remote router {} ({}) detected. This BMP session will be abandoned.",
                 routerIp, session);
-            this.close();
+            close();
         } else {
             routerYangIId = YangInstanceIdentifier.builder(sessionManager.getRoutersYangIId())
                 .nodeWithKey(Router.QNAME, ROUTER_ID_QNAME, routerIp).build();
@@ -259,7 +259,7 @@ public final class BmpRouterImpl implements BmpRouter, DOMTransactionChainListen
         final PeerId peerId = getPeerId((PeerHeader) perPeerMessage);
         final Optional<BmpRouterPeer> maybePeer = getPeer(peerId);
         if (maybePeer.isPresent()) {
-            maybePeer.get().onPeerMessage(perPeerMessage);
+            maybePeer.orElseThrow().onPeerMessage(perPeerMessage);
             if (perPeerMessage instanceof PeerDownNotification) {
                 peers.remove(peerId);
                 LOG.debug("Router {}: Peer {} removed.", routerIp, peerId.getValue());
index f53421419f05710c2308d25501d48db1b4742966..ffbeacb464100fdf13317fabd6865d6f3904a4f8 100644 (file)
@@ -26,8 +26,8 @@ public enum TerminationReason {
         final TerminationReason[] reasons = TerminationReason.values();
         verify(reasons.length > 0);
 
-        final short highest = Arrays.stream(reasons).map(TerminationReason::getUintValue).max(Uint8::compareTo).get()
-                .toJava();
+        final short highest = Arrays.stream(reasons).map(TerminationReason::getUintValue).max(Uint8::compareTo)
+            .orElseThrow().toJava();
         final TerminationReason[] init = new TerminationReason[highest + 1];
         for (TerminationReason reason : reasons) {
             init[reason.getUintValue().toJava()] = reason;
index 846d7d640a44a3cf84a34199a5cf77314962a6ab..abaf4104d89d8cc266a76749eff8bb73e150303d 100755 (executable)
@@ -159,6 +159,6 @@ public final class Main {
 
     private static ch.qos.logback.classic.Logger getRootLogger(final LoggerContext lc) {
         return lc.getLoggerList().stream().filter(input -> input != null && input.getName()
-            .equals(Logger.ROOT_LOGGER_NAME)).findFirst().get();
+            .equals(Logger.ROOT_LOGGER_NAME)).findFirst().orElseThrow();
     }
 }
index 1b4002bbeb27efac2717414c6a388fff1c8cfdf8..54014bac2beef531d060ede36416feaac0bb4697 100644 (file)
@@ -22,7 +22,6 @@ import com.google.common.net.InetAddresses;
 import io.netty.util.Timeout;
 import io.netty.util.Timer;
 import java.net.InetAddress;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -78,7 +77,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
         Preconditions.checkArgument(lspsCount >= 0);
         this.redelegationTimeout = redelegationTimeout;
         this.stateTimeout = stateTimeout;
-        this.plspIDsCounter = new AtomicLong(lspsCount);
+        plspIDsCounter = new AtomicLong(lspsCount);
         this.address = InetAddresses.toAddrString(requireNonNull(address));
         this.timer = requireNonNull(timer);
         this.timerHandler = timerHandler;
@@ -87,7 +86,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     protected void reportToAll(final Updates update, final PCCSession session) {
         final PlspId plspId = update.getLsp().getPlspId();
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         final Uint32 srpId = update.getSrp().getOperationId().getValue();
         if (tunnel != null) {
             if (hasDelegation(tunnel, session)) {
@@ -108,7 +107,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     private void returnDelegation(final Updates update, final PCCSession session) {
         final PlspId plspId = update.getLsp().getPlspId();
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         final Uint32 srpId = update.getSrp().getOperationId().getValue();
         if (tunnel != null) {
             //check if session really has a delegation
@@ -138,7 +137,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     protected void takeDelegation(final Requests request, final PCCSession session) {
         final PlspId plspId = request.getLsp().getPlspId();
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         final Uint32 srpId = request.getSrp().getOperationId().getValue();
         if (tunnel != null) {
             //check if tunnel has no delegation
@@ -163,25 +162,25 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     @Override
     public synchronized void onSessionUp(final PCCSession session) {
-        this.syncOptimization = new PCCSyncOptimization(session);
+        syncOptimization = new PCCSyncOptimization(session);
         lazyTunnelInicialization();
 
         //first session - delegate all PCC's LSPs only when reporting at startup
-        if (!this.sessions.containsKey(session.getId()) && session.getId() == 0) {
-            for (final PlspId plspId : this.tunnels.keySet()) {
+        if (!sessions.containsKey(session.getId()) && session.getId() == 0) {
+            for (final PlspId plspId : tunnels.keySet()) {
                 setDelegation(plspId, session);
             }
         }
-        this.sessions.put(session.getId(), session);
+        sessions.put(session.getId(), session);
 
-        if (!this.syncOptimization.isTriggeredInitSyncEnabled()) {
+        if (!syncOptimization.isTriggeredInitSyncEnabled()) {
             lspReport(session);
         }
     }
 
     @Override
     public synchronized void onSessionDown(final PCCSession session) {
-        for (final Entry<PlspId, PCCTunnel> entry : this.tunnels.entrySet()) {
+        for (final Entry<PlspId, PCCTunnel> entry : tunnels.entrySet()) {
             final PCCTunnel tunnel = entry.getValue();
             final PlspId plspId = entry.getKey();
             //deal with delegations
@@ -193,24 +192,24 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
     }
 
     protected void addTunnel(final Requests request, final PCCSession session) {
-        final PlspId plspId = new PlspId(Uint32.valueOf(this.plspIDsCounter.incrementAndGet()));
+        final PlspId plspId = new PlspId(Uint32.valueOf(plspIDsCounter.incrementAndGet()));
         final PCCTunnel tunnel = new PCCTunnel(request.getLsp().getTlvs().getSymbolicPathName()
                 .getPathName().getValue(), session.getId(), LspType.PCE_LSP, reqToRptPath(request));
         sendToAll(tunnel, plspId, request.getEro().getSubobject(),
                 createSrp(request.getSrp().getOperationId().getValue()), tunnel.getLspState(),
                 new LspBuilder(request.getLsp())
                         .addAugmentation(new Lsp1Builder().setCreate(true).build()).build());
-        this.tunnels.put(plspId, tunnel);
+        tunnels.put(plspId, tunnel);
     }
 
     protected void removeTunnel(final Requests request, final PCCSession session) {
         final PlspId plspId = request.getLsp().getPlspId();
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         final Uint32 srpId = request.getSrp().getOperationId().getValue();
         if (tunnel != null) {
             if (tunnel.getType() == LspType.PCE_LSP) {
                 if (hasDelegation(tunnel, session)) {
-                    this.tunnels.remove(plspId);
+                    tunnels.remove(plspId);
                     sendToAll(tunnel, plspId, tunnel.getLspState().getEro().getSubobject(),
                         new SrpBuilder(request.getSrp())
                                 .addAugmentation(new Srp1Builder().setRemove(true).build()).build(),
@@ -231,9 +230,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
         final Lsp lsp = update.getLsp();
         if (isInitialSyncTriggered(lsp)) {
             lspReport(session);
-            if (this.timerHandler.isPresent()) {
-                this.timerHandler.get().createDisconnectTask();
-            }
+            timerHandler.ifPresent(TimerHandler::createDisconnectTask);
         } else if (isReSyncTriggered(lsp)) {
             handledDbTriggeredResync(update, session);
         } else if (Boolean.TRUE.equals(lsp.getDelegate())) {
@@ -262,36 +259,36 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     private Tlvs buildTlvs(final PCCTunnel tunnel, final Uint32 plspId,
             final Optional<List<Subobject>> subobjectsList) {
-        final List<Subobject> subObject = subobjectsList.isPresent() ? subobjectsList.get() :
-                tunnel.getLspState().getEro().getSubobject();
-        final String destinationAddress = getDestinationAddress(subObject, this.address);
+        final var subObject = subobjectsList.isPresent() ? subobjectsList.orElseThrow()
+            : tunnel.getLspState().getEro().getSubobject();
+        final String destinationAddress = getDestinationAddress(subObject, address);
 
-        return createLspTlvs(plspId, true, destinationAddress, this.address, this.address,
-                Optional.of(tunnel.getPathName()), this.syncOptimization.incrementLspDBVersion());
+        return createLspTlvs(plspId, true, destinationAddress, address, address,
+                Optional.of(tunnel.getPathName()), syncOptimization.incrementLspDBVersion());
     }
 
     private synchronized void lazyTunnelInicialization() {
-        if (this.tunnels.isEmpty()) {
-            final Uint64 dbV = this.syncOptimization.getLocalLspDbVersionValue();
-            if (dbV != null && this.syncOptimization.isSyncAvoidanceEnabled() && !dbV.equals(Uint64.ONE)) {
-                this.tunnels.putAll(PCCTunnelBuilder.createTunnels(this.address, dbV.intValue()));
+        if (tunnels.isEmpty()) {
+            final Uint64 dbV = syncOptimization.getLocalLspDbVersionValue();
+            if (dbV != null && syncOptimization.isSyncAvoidanceEnabled() && !dbV.equals(Uint64.ONE)) {
+                tunnels.putAll(PCCTunnelBuilder.createTunnels(address, dbV.intValue()));
             } else {
-                this.tunnels.putAll(PCCTunnelBuilder.createTunnels(this.address, this.lspsCount));
+                tunnels.putAll(PCCTunnelBuilder.createTunnels(address, lspsCount));
             }
         }
     }
 
     private boolean isReSyncTriggered(final Lsp lsp) {
-        return this.syncOptimization.isTriggeredReSyncEnabled() && lsp.getSync();
+        return syncOptimization.isTriggeredReSyncEnabled() && lsp.getSync();
     }
 
     private boolean isInitialSyncTriggered(final Lsp lsp) {
         return lsp.getPlspId().getValue().toJava() == 0 && lsp.getSync()
-                && this.syncOptimization.isTriggeredInitSyncEnabled();
+                && syncOptimization.isTriggeredInitSyncEnabled();
     }
 
     private void handledDbTriggeredResync(final Updates update, final PCCSession session) {
-        this.syncOptimization.setResynchronizingState(true);
+        syncOptimization.setResynchronizingState(true);
         final SrpIdNumber operationId = update.getSrp().getOperationId();
         if (update.getLsp().getPlspId().getValue().toJava() == 0) {
             reportAllKnownLsp(Optional.of(operationId), session);
@@ -299,16 +296,16 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
             reportLsp(update.getLsp().getPlspId(), operationId, session);
         }
         sendEndOfSynchronization(session, Optional.of(operationId));
-        this.syncOptimization.setResynchronizingState(false);
+        syncOptimization.setResynchronizingState(false);
     }
 
     private void lspReport(final PCCSession session) {
-        if (!this.tunnels.isEmpty()) {
-            if (!this.syncOptimization.isSyncAvoidanceEnabled()) {
+        if (!tunnels.isEmpty()) {
+            if (!syncOptimization.isSyncAvoidanceEnabled()) {
                 reportAllKnownLsp(session);
                 sendEndOfSynchronization(session);
-            } else if (!this.syncOptimization.doesLspDbMatch()) {
-                if (this.syncOptimization.isDeltaSyncEnabled()) {
+            } else if (!syncOptimization.doesLspDbMatch()) {
+                if (syncOptimization.isDeltaSyncEnabled()) {
                     reportMissedLsp(session);
                     sendEndOfSynchronization(session);
                 } else {
@@ -323,11 +320,11 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
      * Reports Missed Lsp when DbVersion doesnt match.
      */
     private void reportMissedLsp(final PCCSession session) {
-        for (long missedLsp = this.syncOptimization.getRemoteLspDbVersionValue().longValue() + 1;
-             missedLsp <= this.syncOptimization.getLocalLspDbVersionValue().longValue(); missedLsp++) {
+        for (long missedLsp = syncOptimization.getRemoteLspDbVersionValue().longValue() + 1;
+             missedLsp <= syncOptimization.getLocalLspDbVersionValue().longValue(); missedLsp++) {
             final Uint32 missed = Uint32.valueOf(missedLsp);
             final PlspId plspId = new PlspId(missed);
-            final PCCTunnel tunnel = this.tunnels.get(plspId);
+            final PCCTunnel tunnel = tunnels.get(plspId);
             createLspAndSendReport(missed, tunnel, session, Optional.empty(), NO_SRP);
         }
     }
@@ -339,11 +336,11 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
             tunnel.cancelTimeouts();
         }
         final String destinationAddress
-                = getDestinationAddress(tunnel.getLspState().getEro().getSubobject(), this.address);
-        final Tlvs tlvs = createLspTlvs(plspId, true, destinationAddress, this.address,
-                this.address, Optional.of(tunnel.getPathName()), this.syncOptimization.incrementLspDBVersion());
+                = getDestinationAddress(tunnel.getLspState().getEro().getSubobject(), address);
+        final Tlvs tlvs = createLspTlvs(plspId, true, destinationAddress, address,
+                address, Optional.of(tunnel.getPathName()), syncOptimization.incrementLspDBVersion());
 
-        final boolean sync = isSync.isPresent() ? isSync.get() : this.syncOptimization.isSyncNeedIt();
+        final boolean sync = isSync.isPresent() ? isSync.orElseThrow() : syncOptimization.isSyncNeedIt();
         final Lsp lsp = createLsp(plspId, sync, Optional.ofNullable(tlvs), delegation, false);
         final Pcrpt pcrtp = createPcRtpMessage(lsp, srp, tunnel.getLspState());
         session.sendReport(pcrtp);
@@ -354,16 +351,11 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
     }
 
     private void sendEndOfSynchronization(final PCCSession session, final Optional<SrpIdNumber> operationId) {
-        Srp srp = null;
-        if (operationId.isPresent()) {
-            srp = new SrpBuilder().setOperationId(operationId.get()).build();
-        }
-        Optional<Tlvs> tlv = Optional.empty();
-        if (this.syncOptimization.isSyncAvoidanceEnabled()) {
-            tlv = createLspTlvsEndofSync(this.syncOptimization.incrementLspDBVersion().get());
-        }
-        final Pcrpt pcrtp = createPcRtpMessage(createLsp(Uint32.ZERO, false, tlv, true, false),
-                Optional.ofNullable(srp), createPath(Collections.emptyList()));
+        final var srp = operationId.map(id -> new SrpBuilder().setOperationId(id).build());
+        final var tlv = syncOptimization.isSyncAvoidanceEnabled()
+            ? createLspTlvsEndofSync(syncOptimization.incrementLspDBVersion().orElseThrow()) : Optional.<Tlvs>empty();
+        final Pcrpt pcrtp = createPcRtpMessage(createLsp(Uint32.ZERO, false, tlv, true, false), srp,
+            createPath(List.of()));
         session.sendReport(pcrtp);
     }
 
@@ -372,20 +364,15 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
     }
 
     private void reportAllKnownLsp(final Optional<SrpIdNumber> operationId, final PCCSession session) {
-        Srp srp = null;
-        if (operationId.isPresent()) {
-            srp = new SrpBuilder().setOperationId(operationId.get()).build();
-        }
+        final var srp = operationId.map(id -> new SrpBuilder().setOperationId(id).build());
 
-        for (final Entry<PlspId, PCCTunnel> entry : this.tunnels.entrySet()) {
-            final PCCTunnel tunnel = entry.getValue();
-            final Uint32 plspId = entry.getKey().getValue();
-            createLspAndSendReport(plspId, tunnel, session, Optional.empty(), Optional.ofNullable(srp));
+        for (var entry : tunnels.entrySet()) {
+            createLspAndSendReport(entry.getKey().getValue(), entry.getValue(), session, Optional.empty(), srp);
         }
     }
 
     private void reportLsp(final PlspId plspId, final SrpIdNumber operationId, final PCCSession session) {
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         if (tunnel == null) {
             return;
         }
@@ -395,7 +382,7 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
 
     private void sendToAll(final PCCTunnel tunnel, final PlspId plspId, final List<Subobject> subobjects, final Srp srp,
             final Path path, final Lsp lsp) {
-        for (final PCCSession session : this.sessions.values()) {
+        for (final PCCSession session : sessions.values()) {
             final boolean isDelegated = hasDelegation(tunnel, session);
             final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.of(subobjects));
 
@@ -413,21 +400,21 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
     }
 
     private void startStateTimeout(final PCCTunnel tunnel, final PlspId plspId) {
-        if (this.stateTimeout > -1) {
-            final Timeout newStateTimeout = this.timer.newTimeout(timeout -> {
+        if (stateTimeout > -1) {
+            final Timeout newStateTimeout = timer.newTimeout(timeout -> {
                 if (tunnel.getType() == LspType.PCE_LSP) {
                     PCCTunnelManagerImpl.this.tunnels.remove(plspId);
                     //report tunnel removal to all
-                    sendToAll(tunnel, plspId, Collections.emptyList(), createSrp(Uint32.ZERO),
-                        new PathBuilder().build(), createLsp(plspId.getValue(), false, Optional.empty(), false, true));
+                    sendToAll(tunnel, plspId, List.of(), createSrp(Uint32.ZERO), new PathBuilder().build(),
+                        createLsp(plspId.getValue(), false, Optional.empty(), false, true));
                 }
-            }, this.stateTimeout, TimeUnit.SECONDS);
+            }, stateTimeout, TimeUnit.SECONDS);
             tunnel.setStateTimeout(newStateTimeout);
         }
     }
 
     private void startRedelegationTimer(final PCCTunnel tunnel, final PlspId plspId, final PCCSession session) {
-        final Timeout newRedelegationTimeout = this.timer.newTimeout(timeout -> {
+        final Timeout newRedelegationTimeout = timer.newTimeout(timeout -> {
             //remove delegation
             PCCTunnelManagerImpl.this.setDelegation(plspId, null);
             //delegate to another PCE
@@ -449,12 +436,12 @@ public final class PCCTunnelManagerImpl implements PCCTunnelManager {
                     break;
                 }
             }
-        }, this.redelegationTimeout, TimeUnit.SECONDS);
+        }, redelegationTimeout, TimeUnit.SECONDS);
         tunnel.setRedelegationTimeout(newRedelegationTimeout);
     }
 
     private void setDelegation(final PlspId plspId, final PCCSession session) {
-        final PCCTunnel tunnel = this.tunnels.get(plspId);
+        final PCCTunnel tunnel = tunnels.get(plspId);
         final int sessionId;
         if (session != null) {
             sessionId = session.getId();
index ce6e978ac1f9028085ab03fbdbf9fb11b6dc10f8..369d5edd093b2f49e68f155fdd1f5f3b4eea485b 100644 (file)
@@ -70,9 +70,8 @@ final class PCCsBuilder {
         InetAddress currentAddress = localAddress.getAddress();
         PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(registry);
 
-        if (timerHandler.isPresent()) {
-            timerHandler.get().setPCCDispatcher(pccDispatcher);
-        }
+        timerHandler.ifPresent(handler -> handler.setPCCDispatcher(pccDispatcher));
+
         for (int i = 0; i < pccCount; i++) {
             final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(lsps, currentAddress,
                 redelegationTimeout, stateTimeout, timer, timerHandler);
index 257616c97fec0421af2b1c01e6e8d55a42da5dfb..2df8828be494a5219bdb5bbaa7a6e3d6b32a0edd 100644 (file)
@@ -7,9 +7,7 @@
  */
 package org.opendaylight.protocol.pcep.pcc.mock.spi;
 
-import com.google.common.collect.Lists;
 import java.nio.charset.StandardCharsets;
-import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
@@ -63,7 +61,7 @@ public final class MsgBuilderUtil {
     public static Pcrpt createPcRtpMessage(final Lsp lsp, final Optional<Srp> srp, final Path path) {
         return new PcrptBuilder()
                 .setPcrptMessage(new PcrptMessageBuilder()
-                    .setReports(Lists.newArrayList(new ReportsBuilder()
+                    .setReports(List.of(new ReportsBuilder()
                         .setLsp(lsp)
                         .setSrp(srp.orElse(null))
                         .setPath(path).build()))
@@ -143,18 +141,21 @@ public final class MsgBuilderUtil {
                                         .build()).build()).setTunnelId(new TunnelId(Uint16.valueOf(lspId))).build());
         if (symbolicPathName) {
             if (symbolicName.isPresent()) {
-                tlvs.setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(
-                        new SymbolicPathName(symbolicName.get())).build());
+                tlvs.setSymbolicPathName(new SymbolicPathNameBuilder()
+                    .setPathName(new SymbolicPathName(symbolicName.orElseThrow()))
+                    .build());
             } else {
-                tlvs.setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(
-                        new SymbolicPathName(getDefaultPathName(tunnelSender, lspId))).build());
+                tlvs.setSymbolicPathName(new SymbolicPathNameBuilder()
+                    .setPathName(new SymbolicPathName(getDefaultPathName(tunnelSender, lspId)))
+                    .build());
             }
         }
 
-        if (lspDBVersion.isPresent()) {
+        lspDBVersion.ifPresent(dbVersion -> {
             tlvs.addAugmentation(new Tlvs1Builder()
-                .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(lspDBVersion.get()).build()).build());
-        }
+                .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(dbVersion).build())
+                .build());
+        });
         return tlvs.build();
     }
 
@@ -169,7 +170,7 @@ public final class MsgBuilderUtil {
                 .setPcerrMessage(new PcerrMessageBuilder()
                     .setErrorType(new StatefulCaseBuilder()
                         .setStateful(new StatefulBuilder()
-                            .setSrps(Collections.singletonList(new SrpsBuilder()
+                            .setSrps(List.of(new SrpsBuilder()
                                 .setSrp(new SrpBuilder()
                                     .setProcessingRule(false)
                                     .setIgnore(false)
@@ -178,7 +179,7 @@ public final class MsgBuilderUtil {
                                 .build()))
                             .build())
                         .build())
-                    .setErrors(Collections.singletonList(new ErrorsBuilder()
+                    .setErrors(List.of(new ErrorsBuilder()
                         .setErrorObject(new ErrorObjectBuilder()
                             .setType(pcepErrors.getErrorType())
                             .setValue(pcepErrors.getErrorValue())
index 0c688f9bae83fc0329a30c89bc827e34e328c1d4..ff74dd47f74590a5a15635e7bedb734d8fd0907f 100644 (file)
@@ -14,7 +14,6 @@ import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufUtil;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Optional;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.iana.rev130816.EnterpriseNumber;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Tlv;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.vendor.information.tlvs.VendorInformationTlv;
@@ -40,28 +39,25 @@ public abstract class AbstractObjectWithTlvsParser<T> extends CommonObjectParser
         if (!bytes.isReadable()) {
             return;
         }
-        final List<VendorInformationTlv> viTlvs = new ArrayList<>();
+        final var viTlvs = new ArrayList<VendorInformationTlv>();
         while (bytes.isReadable()) {
             final int type = bytes.readUnsignedShort();
             final int length = bytes.readUnsignedShort();
             if (length > bytes.readableBytes()) {
                 throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
-            + bytes.readableBytes()
-                    + ".");
+                    + bytes.readableBytes() + ".");
             }
-            final ByteBuf tlvBytes = bytes.readSlice(length);
+            final var tlvBytes = bytes.readSlice(length);
             LOG.trace("Parsing PCEP TLV : {}", ByteBufUtil.hexDump(tlvBytes));
 
             if (VendorInformationUtil.isVendorInformationTlv(type)) {
-                final EnterpriseNumber enterpriseNumber = new EnterpriseNumber(ByteBufUtils.readUint32(tlvBytes));
-                final Optional<VendorInformationTlv> viTlv = this.viTlvReg.parseVendorInformationTlv(enterpriseNumber,
-                    tlvBytes);
-                if (viTlv.isPresent()) {
-                    LOG.trace("Parsed VENDOR-INFORMATION TLV {}.", viTlv.get());
-                    viTlvs.add(viTlv.get());
-                }
+                final var enterpriseNumber = new EnterpriseNumber(ByteBufUtils.readUint32(tlvBytes));
+                viTlvReg.parseVendorInformationTlv(enterpriseNumber, tlvBytes).ifPresent(viTlv -> {
+                    LOG.trace("Parsed VENDOR-INFORMATION TLV {}.", viTlv);
+                    viTlvs.add(viTlv);
+                });
             } else {
-                final Tlv tlv = this.tlvReg.parseTlv(type, tlvBytes);
+                final Tlv tlv = tlvReg.parseTlv(type, tlvBytes);
                 if (tlv != null) {
                     LOG.trace("Parsed PCEP TLV {}.", tlv);
                     addTlv(builder, tlv);
@@ -75,7 +71,7 @@ public abstract class AbstractObjectWithTlvsParser<T> extends CommonObjectParser
     protected final void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
         requireNonNull(tlv, "PCEP TLV is mandatory.");
         LOG.trace("Serializing PCEP TLV {}", tlv);
-        this.tlvReg.serializeTlv(tlv, buffer);
+        tlvReg.serializeTlv(tlv, buffer);
         LOG.trace("Serialized PCEP TLV : {}.", ByteBufUtil.hexDump(buffer));
     }
 
@@ -87,9 +83,9 @@ public abstract class AbstractObjectWithTlvsParser<T> extends CommonObjectParser
 
     protected final void serializeVendorInformationTlvs(final List<VendorInformationTlv> tlvs, final ByteBuf buffer) {
         if (tlvs != null) {
-            for (final VendorInformationTlv tlv : tlvs) {
+            for (var tlv : tlvs) {
                 LOG.trace("Serializing VENDOR-INFORMATION TLV {}", tlv);
-                this.viTlvReg.serializeVendorInformationTlv(tlv, buffer);
+                viTlvReg.serializeVendorInformationTlv(tlv, buffer);
                 LOG.trace("Serialized VENDOR-INFORMATION TLV : {}.", ByteBufUtil.hexDump(buffer));
             }
         }
index 0a1d223e6d07a60a360b30daf5d25013b63a3bd8..2d010be8ee0065e77d37f52d4b2b23485c23da9a 100644 (file)
@@ -457,11 +457,9 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
         final RequestsBuilder rb = new RequestsBuilder();
         final SrpBuilder srpBuilder = new SrpBuilder().addAugmentation(new Srp1Builder()
                 .setRemove(Boolean.TRUE).build()).setOperationId(nextRequest()).setProcessingRule(Boolean.TRUE);
-        final Optional<PathSetupType> maybePST = getPST(rep);
-        if (maybePST.isPresent()) {
-            srpBuilder.setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
-                    .rev200720.srp.object.srp.TlvsBuilder().setPathSetupType(maybePST.get()).build());
-        }
+        getPST(rep).ifPresent(pst -> srpBuilder.setTlvs(
+            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
+                .rev200720.srp.object.srp.TlvsBuilder().setPathSetupType(pst).build()));
         rb.setSrp(srpBuilder.build());
         rb.setLsp(new LspBuilder().setRemove(Boolean.FALSE).setPlspId(reportedLsp.getPlspId())
                 .setDelegate(reportedLsp.getDelegate()).build());
@@ -543,12 +541,12 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
             final ListenableFuture<Optional<ReportedLsp>> future, final EnsureLspOperationalInput input,
             final OperationalStatus op) {
         return Futures.transform(future, rep -> {
-            if (!rep.isPresent()) {
+            if (rep.isEmpty()) {
                 LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
                 return OperationResults.UNSENT;
             }
             // check if at least one of the paths has the same status as requested
-            for (final Path p : rep.get().nonnullPath().values()) {
+            for (final Path p : rep.orElseThrow().nonnullPath().values()) {
                 final Path1 p1 = p.augmentation(Path1.class);
                 if (p1 == null) {
                     LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
@@ -564,12 +562,12 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
 
     @Override
     protected Lsp validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input) {
-        if (!rep.isPresent()) {
+        if (rep.isEmpty()) {
             LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
             return null;
         }
         // it doesn't matter how many lsps there are in the path list, we only need data that is the same in each path
-        final Path1 ra = rep.get().getPath().values().iterator().next().augmentation(Path1.class);
+        final Path1 ra = rep.orElseThrow().getPath().values().iterator().next().augmentation(Path1.class);
         checkState(ra != null, "Reported LSP reported null from data-store.");
         final Lsp reportedLsp = ra.getLsp();
         checkState(reportedLsp != null, "Reported LSP does not contain LSP object.");
@@ -578,7 +576,7 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
 
     private static Optional<PathSetupType> getPST(final Optional<ReportedLsp> rep) {
         if (rep.isPresent()) {
-            final Path1 path1 = rep.get().getPath().values().iterator().next().augmentation(Path1.class);
+            final Path1 path1 = rep.orElseThrow().getPath().values().iterator().next().augmentation(Path1.class);
             if (path1 != null) {
                 final PathSetupType pst = path1.getPathSetupType();
                 if (!PSTUtil.isDefaultPST(pst)) {
@@ -646,11 +644,11 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
         @Override
         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
             final Lsp reportedLsp = validateReportedLsp(rep, input);
-            if (reportedLsp == null || !rep.isPresent()) {
+            if (reportedLsp == null || rep.isEmpty()) {
                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
             }
             // mark lsp as stale
-            final ReportedLsp staleLsp = rep.get();
+            final ReportedLsp staleLsp = rep.orElseThrow();
             if (!staleLsp.getPath().isEmpty()) {
                 final Path1 path1 = staleLsp.getPath().values().iterator().next().augmentation(Path1.class);
                 if (path1 != null) {
@@ -663,13 +661,9 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
             srpBuilder.setOperationId(nextRequest());
             srpBuilder.setProcessingRule(Boolean.TRUE);
 
-            final Optional<PathSetupType> maybePST = getPST(rep);
-            if (maybePST.isPresent()) {
-                srpBuilder.setTlvs(
-                        new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
-                                .rev200720.srp.object.srp.TlvsBuilder()
-                                .setPathSetupType(maybePST.get()).build());
-            }
+            getPST(rep).ifPresent(pst -> srpBuilder.setTlvs(
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
+                    .rev200720.srp.object.srp.TlvsBuilder().setPathSetupType(pst).build()));
 
             final Srp srp = srpBuilder.build();
             final Lsp lsp = new LspBuilder().setPlspId(reportedLsp.getPlspId()).setSync(Boolean.TRUE).build();
@@ -804,13 +798,9 @@ class PCEPTopologySessionListener extends AbstractTopologySessionListener {
                                     .setPathSetupType(args.getPathSetupType()).build());
                 }
             } else {
-                final Optional<PathSetupType> maybePST = getPST(rep);
-                if (maybePST.isPresent()) {
-                    srpBuilder.setTlvs(
-                            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
-                                    .rev200720.srp.object.srp.TlvsBuilder()
-                                    .setPathSetupType(maybePST.get()).build());
-                }
+                getPST(rep).ifPresent(pst -> srpBuilder.setTlvs(
+                    new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful
+                        .rev200720.srp.object.srp.TlvsBuilder().setPathSetupType(pst).build()));
             }
             final Srp srp = srpBuilder.build();
             final Lsp inputLsp = args != null ? args.getLsp() : null;
index 95ab551b473cb8759ec3d2d2664e0e15cb8065c3..8260d236e2f8505c30e83d3740b0072fee6d0953 100644 (file)
@@ -117,11 +117,11 @@ final class TopologyNodeState implements TransactionChainListener {
             try {
                 // FIXME: we really should not be performing synchronous operations
                 final Optional<Node> prevNode = readOperationalData(nodeId).get();
-                if (!prevNode.isPresent()) {
+                if (prevNode.isEmpty()) {
                     putTopologyNode();
                 } else {
                     //cache retrieved node
-                    initialNodeState = prevNode.get();
+                    initialNodeState = prevNode.orElseThrow();
                 }
             } catch (final ExecutionException | InterruptedException throwable) {
                 LOG.error("Failed to get topology node {}", nodeId, throwable);
index 54b806feccedcd8abc8e55dd7602ccf0484258ac..6fd21bfeddf2489fd4f0bc8392e9d4c9b9ede368 100644 (file)
@@ -120,7 +120,7 @@ final class TopologyStatsRpcServiceImpl
                         final var nodes = iTopologies.values().stream()
                             .filter(t -> iTopologyId.equals(t.getTopologyId()))
                             .findFirst()
-                            .get().getNode();
+                            .orElseThrow().getNode();
                         iNodes = nodes != null ? nodes.values() : null;
                     } else {
                         iNodes = null;
index 55d259be454ad18386afe398b3e66385a30689b6..ea190df56f6a67ea87baa787cb3f3343a7a72de4 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.bgpcep.pcep.tunnel.provider;
 
 import static java.util.Objects.requireNonNull;
@@ -77,7 +76,7 @@ final class CreateTunnelInstructionExecutor extends AbstractInstructionExecutor
         final InstanceIdentifier<Link> lii = NodeChangedListener.linkIdentifier(tii, addLspInput.getNode(),
                 addLspInput.getName());
         try {
-            Preconditions.checkState(!rt.read(LogicalDatastoreType.OPERATIONAL, lii).get().isPresent());
+            Preconditions.checkState(!rt.exists(LogicalDatastoreType.OPERATIONAL, lii).get());
         } catch (final InterruptedException | ExecutionException e) {
             throw new IllegalStateException("Failed to ensure link existence.", e);
         }
@@ -110,9 +109,7 @@ final class CreateTunnelInstructionExecutor extends AbstractInstructionExecutor
         }
 
         // We need to have a ret now
-        Preconditions.checkArgument(ret != null, "Failed to find like Endpoint addresses");
-
-        return ret.get();
+        return ret.orElseThrow(() -> new IllegalArgumentException("Failed to find like Endpoint addresses"));
     }
 
     private static Optional<AddressFamily> findIpv4(final Set<IpAddress> srcs, final Set<IpAddress> dsts) {
@@ -214,7 +211,7 @@ final class CreateTunnelInstructionExecutor extends AbstractInstructionExecutor
 
         private DataObject read(final InstanceIdentifier<?> id) {
             try {
-                return rt.read(LogicalDatastoreType.OPERATIONAL, id).get().get();
+                return rt.read(LogicalDatastoreType.OPERATIONAL, id).get().orElseThrow();
             } catch (final InterruptedException | ExecutionException e) {
                 throw new IllegalStateException("Failed to read data.", e);
             }
index 8e2e27e94f1d28d429ca06f15356dc7fade6bcf5..040ab5f3ce7f74b448420ca0af3d0d43cfec57dc 100644 (file)
@@ -47,16 +47,16 @@ final class DestroyTunnelInstructionExecutor extends AbstractInstructionExecutor
 
     @Override
     protected ListenableFuture<OperationResult> invokeOperation() {
-        final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil.topologyForInput(this.pcepDestroyTunnelInput);
-        final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, this.pcepDestroyTunnelInput);
-        try (ReadTransaction t = this.dataProvider.newReadOnlyTransaction()) {
+        final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil.topologyForInput(pcepDestroyTunnelInput);
+        final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, pcepDestroyTunnelInput);
+        try (ReadTransaction t = dataProvider.newReadOnlyTransaction()) {
             final Node node;
             final Link link;
             try {
                 // The link has to exist
-                link = t.read(LogicalDatastoreType.OPERATIONAL, lii).get().get();
+                link = t.read(LogicalDatastoreType.OPERATIONAL, lii).get().orElseThrow();
                 // The source node has to exist
-                node = TunelProgrammingUtil.sourceNode(t, tii, link).get();
+                node = TunelProgrammingUtil.sourceNode(t, tii, link).orElseThrow();
             } catch (final InterruptedException | ExecutionException e) {
                 LOG.debug("Link or node does not exist.", e);
                 return TunelProgrammingUtil.RESULT;
@@ -65,7 +65,7 @@ final class DestroyTunnelInstructionExecutor extends AbstractInstructionExecutor
             ab.setName(link.augmentation(Link1.class).getSymbolicPathName());
             ab.setNode(node.nonnullSupportingNode().values().iterator().next().key().getNodeRef());
             return Futures.transform(
-                    this.topologyService.removeLsp(ab.build()),
+                    topologyService.removeLsp(ab.build()),
                     RpcResult::getResult, MoreExecutors.directExecutor());
         }
     }
index b86afcc6e3f15110bcbf7d194a29a9892fd32ccb..052d62d035a91b7e00a1ad6fbd020b1687ef0364 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.bgpcep.pcep.tunnel.provider;
 
 import static java.util.Objects.requireNonNull;
 
-import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.MoreExecutors;
 import java.util.ArrayList;
@@ -162,8 +161,8 @@ public final class NodeChangedListener implements ClusteredDataTreeChangeListene
             }
             if (!have) {
                 final SupportingNode sn = createSupportingNode(k.getNodeId(), inControl);
-                trans.put(LogicalDatastoreType.OPERATIONAL, target.child(Node.class, node.key()).child(
-                        SupportingNode.class, sn.key()), sn);
+                trans.put(LogicalDatastoreType.OPERATIONAL,
+                    target.child(Node.class, node.key()).child(SupportingNode.class, sn.key()), sn);
             }
         }
     }
@@ -171,7 +170,7 @@ public final class NodeChangedListener implements ClusteredDataTreeChangeListene
     private InstanceIdentifier<TerminationPoint> getIpTerminationPoint(final ReadWriteTransaction trans,
             final IpAddress addr, final InstanceIdentifier<Node> sni, final Boolean inControl)
             throws ExecutionException, InterruptedException {
-        final Topology topo = trans.read(LogicalDatastoreType.OPERATIONAL, target).get().get();
+        final Topology topo = trans.read(LogicalDatastoreType.OPERATIONAL, target).get().orElseThrow();
         for (final Node n : topo.nonnullNode().values()) {
             for (final TerminationPoint tp : n.nonnullTerminationPoint().values()) {
                 final TerminationPoint1 tpa = tp.augmentation(TerminationPoint1.class);
@@ -234,12 +233,12 @@ public final class NodeChangedListener implements ClusteredDataTreeChangeListene
          */
         final IpAddress srcIp;
         final IpAddress dstIp;
-        if (af instanceof Ipv4Case) {
-            final Ipv4 ipv4 = ((Ipv4Case) af).getIpv4();
+        if (af instanceof Ipv4Case ipv4case) {
+            final Ipv4 ipv4 = ipv4case.getIpv4();
             srcIp = new IpAddress(ipv4.getIpv4TunnelSenderAddress());
             dstIp = new IpAddress(ipv4.getIpv4TunnelEndpointAddress());
-        } else if (af instanceof Ipv6Case) {
-            final Ipv6 ipv6 = ((Ipv6Case) af).getIpv6();
+        } else if (af instanceof Ipv6Case ipv6case) {
+            final Ipv6 ipv6 = ipv6case.getIpv6();
             srcIp = new IpAddress(ipv6.getIpv6TunnelSenderAddress());
             dstIp = new IpAddress(ipv6.getIpv6TunnelSenderAddress());
         } else {
@@ -295,19 +294,18 @@ public final class NodeChangedListener implements ClusteredDataTreeChangeListene
         final InstanceIdentifier<Link> li = linkForLsp(linkIdForLsp(identifier, value));
 
         final Optional<Link> ol = trans.read(LogicalDatastoreType.OPERATIONAL, li).get();
-        if (!ol.isPresent()) {
+        if (ol.isEmpty()) {
             return;
         }
 
-        final Link l = ol.get();
+        final Link l = ol.orElseThrow();
         LOG.debug("Removing link {} (was {})", li, l);
         trans.delete(LogicalDatastoreType.OPERATIONAL, li);
 
         LOG.debug("Searching for orphan links/nodes");
         final Optional<Topology> ot = trans.read(LogicalDatastoreType.OPERATIONAL, target).get();
-        Preconditions.checkState(ot.isPresent());
 
-        final Topology topology = ot.get();
+        final Topology topology = ot.orElseThrow(IllegalStateException::new);
         final NodeId srcNode = l.getSource().getSourceNode();
         final NodeId dstNode = l.getDestination().getDestNode();
         final TpId srcTp = l.getSource().getSourceTp();
index 5d8ccf8dc544545735dc4d9c5b80e0bfa91a09b8..29eb2d6e4e4a68bf7092eb773f34fa000cf16c2d 100644 (file)
@@ -56,47 +56,44 @@ final class UpdateTunnelInstructionExecutor extends AbstractInstructionExecutor
 
     @Override
     protected ListenableFuture<OperationResult> invokeOperation() {
-        final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil.topologyForInput(this.updateTunnelInput);
-        final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, this.updateTunnelInput);
-        try (ReadTransaction t = this.dataProvider.newReadOnlyTransaction()) {
+        final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil.topologyForInput(updateTunnelInput);
+        final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, updateTunnelInput);
+        try (ReadTransaction t = dataProvider.newReadOnlyTransaction()) {
             final Link link;
             final Node node;
             try {
                 // The link has to exist
-                link = t.read(LogicalDatastoreType.OPERATIONAL, lii).get().get();
+                link = t.read(LogicalDatastoreType.OPERATIONAL, lii).get().orElseThrow();
                 // The source node has to exist
-                node = TunelProgrammingUtil.sourceNode(t, tii, link).get();
+                node = TunelProgrammingUtil.sourceNode(t, tii, link).orElseThrow();
             } catch (final InterruptedException | ExecutionException e) {
                 LOG.debug("Link or node does not exist.", e);
                 return TunelProgrammingUtil.RESULT;
             }
             return Futures.transform(
-                    this.topologyService
-                            .updateLsp(buildUpdateInput(link, node)),
-                    RpcResult::getResult, MoreExecutors.directExecutor());
+                topologyService.updateLsp(buildUpdateInput(link, node)),
+                RpcResult::getResult, MoreExecutors.directExecutor());
         }
     }
 
     private UpdateLspInput buildUpdateInput(final Link link, final Node node) {
-        final UpdateLspInputBuilder ab = new UpdateLspInputBuilder();
-        ab.setName(link.augmentation(Link1.class).getSymbolicPathName());
-        ab.setNode(requireNonNull(TunelProgrammingUtil.supportingNode(node)));
+        final UpdateLspInputBuilder ab = new UpdateLspInputBuilder()
+            .setName(link.augmentation(Link1.class).getSymbolicPathName())
+            .setNode(requireNonNull(TunelProgrammingUtil.supportingNode(node)));
 
-        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev220730.update.lsp
-                .args.ArgumentsBuilder args = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
-                .yang.topology.pcep.rev220730.update.lsp.args.ArgumentsBuilder();
-        args.setBandwidth(new BandwidthBuilder().setBandwidth(this.updateTunnelInput.getBandwidth()).build());
-        args.setClassType(new ClassTypeBuilder().setClassType(this.updateTunnelInput.getClassType()).build());
-        args.setEro(TunelProgrammingUtil.buildEro(this.updateTunnelInput.getExplicitHops()));
-        args.setLspa(new LspaBuilder(this.updateTunnelInput).build());
+        final var args = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev220730
+            .update.lsp.args.ArgumentsBuilder()
+                .setBandwidth(new BandwidthBuilder().setBandwidth(updateTunnelInput.getBandwidth()).build())
+                .setClassType(new ClassTypeBuilder().setClassType(updateTunnelInput.getClassType()).build())
+                .setEro(TunelProgrammingUtil.buildEro(updateTunnelInput.getExplicitHops()))
+                .setLspa(new LspaBuilder(updateTunnelInput).build());
 
-        final AdministrativeStatus adminStatus = this.updateTunnelInput.augmentation(PcepUpdateTunnelInput1.class)
+        final AdministrativeStatus adminStatus = updateTunnelInput.augmentation(PcepUpdateTunnelInput1.class)
                 .getAdministrativeStatus();
         if (adminStatus != null) {
             args.addAugmentation(new Arguments3Builder().setLsp(new LspBuilder()
                     .setAdministrative(adminStatus == AdministrativeStatus.Active).build()).build());
         }
-        ab.setArguments(args.build());
-        return ab.build();
+        return ab.setArguments(args.build()).build();
     }
 }
index 7696e33bae0b305ed78879f99e918b9922c2b4eb..97d1d153374d8eda7f8a644329cfad264855bb08 100644 (file)
@@ -77,7 +77,7 @@ public final class CheckTestUtil {
                 final Optional<T> data = tx.read(ldt, iid).get();
                 if (data.isPresent()) {
                     try {
-                        return function.apply(data.get());
+                        return function.apply(data.orElseThrow());
                     } catch (final AssertionError e) {
                         lastError = e;
                         Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);