}
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);
}
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());
}
}
*/
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;
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));
}
}
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);
}
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) {
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;
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());
}
}
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) {
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);
}
}
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
}
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()
);
}
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;
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
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
);
}
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
);
}
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);
}
}
*/
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;
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;
/**
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());
}
}
*/
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;
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 {
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();
}
}
}
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;
}
}
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;
}
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;
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();
}
LOG.warn("Routes {} are not a map", routes);
}
- return Collections.emptyList();
+ return List.of();
}
@Override
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)));
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;
}
= (DestinationLinkstateCase) withdrawnRoutes.getDestinationType();
for (final CLinkstateDestination linkstateDestinationCase : linkstateCase.getDestinationLinkstate()
.getCLinkstateDestination()) {
- this.nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
+ nlriTypeReg.serializeNlriType(linkstateDestinationCase, byteAggregator);
}
}
}
.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;
}
}
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())
}
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) {
}
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());
}
}
}
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;
+ };
}
}
}
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));
}
}
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;
@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();
}
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;
private static final ClientAttributePrependHandler INSTANCE = new ClientAttributePrependHandler();
private ClientAttributePrependHandler() {
-
+ // Hidden on purpose
}
public static ClientAttributePrependHandler getInstance() {
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
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
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);
}
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;
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);
}
} 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 {
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);
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;
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;
}
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));
}
*/
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;
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);
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);
}
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
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()));
}
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;
}
}
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());
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:
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;
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,
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
// 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());
}
}
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);
}
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;
}
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:
optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
}
- if (!optEffAtt.isPresent()) {
+ if (optEffAtt.isEmpty()) {
deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
return;
}
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);
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;
}
}
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>>
}
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
}
}, 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);
}
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;
}
@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);
/*
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);
}
}
/*
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 -> {
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);
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()) {
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));
@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);
}
}
}
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));
}
* @return Container identifier, may not be null.
*/
public final NodeIdentifier routesContainerIdentifier() {
- return this.routesContainerIdentifier;
+ return routesContainerIdentifier;
}
/**
* @return Container identifier, may not be null.
*/
private NodeIdentifier destinationContainerIdentifier() {
- return this.destinationNid;
+ return destinationNid;
}
/**
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,
@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.
}
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) {
@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());
}
// 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;
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();
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());
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;
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();
}
}
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;
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;
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)) {
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
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
@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
}
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(),
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())) {
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);
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 {
* 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);
}
}
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);
}
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);
}
}
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;
}
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));
}
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
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();
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);
*/
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;
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()))
.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();
}
.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)
.build()))
.build())
.build())
- .setErrors(Collections.singletonList(new ErrorsBuilder()
+ .setErrors(List.of(new ErrorsBuilder()
.setErrorObject(new ErrorObjectBuilder()
.setType(pcepErrors.getErrorType())
.setValue(pcepErrors.getErrorValue())
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;
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);
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));
}
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));
}
}
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());
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());
@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.");
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)) {
@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) {
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();
.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;
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);
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;
* 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;
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);
}
}
// 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) {
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);
}
@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;
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());
}
}
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;
}
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);
}
}
}
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);
*/
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 {
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();
@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();
}
}
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);