@Override
public void close() throws Exception {
- this.channel.close().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture channelFuture) throws Exception {
- BmpMonitoringStationImpl.this.sessionManager.close();
- }
- }).await();
+ this.channel.close().addListener((ChannelFutureListener) channelFuture -> BmpMonitoringStationImpl.this.sessionManager.close()).await();
final DOMDataWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
wTx.delete(LogicalDatastoreType.OPERATIONAL, this.yangMonitorId);
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
import org.opendaylight.protocol.bgp.parser.spi.AddressFamilyRegistry;
import org.opendaylight.protocol.bgp.parser.spi.BGPExtensionProviderContext;
public class AbstractBmpModuleTest extends AbstractConfigTest {
@Before
public void setUp() throws Exception {
- doAnswer(new Answer<Filter>() {
- @Override
- public Filter answer(final InvocationOnMock invocation) {
- final String str = invocation.getArgumentAt(0, String.class);
- final Filter mockFilter = mock(Filter.class);
- doReturn(str).when(mockFilter).toString();
- return mockFilter;
- }
+ doAnswer(invocation -> {
+ final String str = invocation.getArgumentAt(0, String.class);
+ final Filter mockFilter = mock(Filter.class);
+ doReturn(str).when(mockFilter).toString();
+ return mockFilter;
}).when(mockedContext).createFilter(anyString());
Mockito.doNothing().when(this.mockedContext).addServiceListener(any(ServiceListener.class), Mockito.anyString());
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
final SchemaContext context = parseYangStreams(getFilesAsByteSources(getYangModelsPaths()));
final SchemaService mockedSchemaService = mock(SchemaService.class);
doReturn(context).when(mockedSchemaService).getGlobalContext();
- doAnswer(new Answer<ListenerRegistration<SchemaContextListener>>() {
- @Override
- public ListenerRegistration<SchemaContextListener> answer(InvocationOnMock invocation) {
- invocation.getArgumentAt(0, SchemaContextListener.class).onGlobalContextUpdated(context);
- ListenerRegistration<SchemaContextListener> reg = mock(ListenerRegistration.class);
- doNothing().when(reg).close();
- return reg;
- }
+ doAnswer(invocation -> {
+ invocation.getArgumentAt(0, SchemaContextListener.class).onGlobalContextUpdated(context);
+ final ListenerRegistration<SchemaContextListener> reg = mock(ListenerRegistration.class);
+ doNothing().when(reg).close();
+ return reg;
}).when(mockedSchemaService).registerSchemaContextListener(any(SchemaContextListener.class));
setupMockService(SchemaService.class, mockedSchemaService);
setupMockService(YangTextSourceProvider.class, mock(YangTextSourceProvider.class));
Mockito.doReturn(mockedSchemaService).when(this.mockedContext).getService(schemaServiceReference);
- BindingToNormalizedNodeCodec bindingCodec = BindingToNormalizedNodeCodecFactory.newInstance(
+ final BindingToNormalizedNodeCodec bindingCodec = BindingToNormalizedNodeCodecFactory.newInstance(
GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
BindingToNormalizedNodeCodecFactory.registerInstance(bindingCodec, mockedSchemaService);
setupMockService(BindingToNormalizedNodeCodec.class, bindingCodec);
- BmpDispatcher bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(),
+ final BmpDispatcher bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(),
new SimpleBmpMessageRegistry(), new DefaultBmpSessionFactory());
setupMockService(BmpDispatcher.class, bmpDispatcher);
}
import org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleBGPExtensionProviderContext;
import org.opendaylight.protocol.bmp.api.BmpDispatcher;
import org.opendaylight.protocol.bmp.api.BmpSession;
-import org.opendaylight.protocol.bmp.api.BmpSessionFactory;
import org.opendaylight.protocol.bmp.api.BmpSessionListenerFactory;
import org.opendaylight.protocol.bmp.impl.BmpDispatcherImpl;
import org.opendaylight.protocol.bmp.parser.BmpActivator;
this.bmpActivator.start(ctx);
final BmpMessageRegistry messageRegistry = ctx.getBmpMessageRegistry();
- this.dispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), messageRegistry, new BmpSessionFactory() {
- @Override
- public BmpSession getSession(final Channel channel,
- final BmpSessionListenerFactory sessionListenerFactory) {
- return BmpDispatcherImplTest.this.mockedSession;
- }
- });
+ this.dispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), messageRegistry, (channel, sessionListenerFactory) -> BmpDispatcherImplTest.this.mockedSession);
}
@After
package org.opendaylight.protocol.bmp.mock;
import com.google.common.net.InetAddresses;
-import io.netty.channel.Channel;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.opendaylight.protocol.bgp.parser.impl.BGPActivator;
import org.opendaylight.protocol.bgp.parser.spi.BGPExtensionProviderContext;
import org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleBGPExtensionProviderContext;
-import org.opendaylight.protocol.bmp.api.BmpSession;
-import org.opendaylight.protocol.bmp.api.BmpSessionFactory;
-import org.opendaylight.protocol.bmp.api.BmpSessionListenerFactory;
import org.opendaylight.protocol.bmp.parser.BmpActivator;
import org.opendaylight.protocol.bmp.spi.registry.BmpExtensionProviderActivator;
import org.opendaylight.protocol.bmp.spi.registry.BmpExtensionProviderContext;
bmpActivator.start(ctx);
return new BmpMockDispatcher(ctx.getBmpMessageRegistry(),
- new BmpSessionFactory() {
- @Override
- public BmpSession getSession(final Channel channel,
- final BmpSessionListenerFactory sessionListenerFactory) {
- return new BmpMockSession(arguments.getPeersCount(), arguments.getPrePolicyRoutesCount(), arguments.getPostPolicyRoutesCount());
- }
- });
+ (channel, sessionListenerFactory) -> new BmpMockSession(arguments.getPeersCount(), arguments.getPrePolicyRoutesCount(), arguments.getPostPolicyRoutesCount()));
}
private static void deployClients(final BmpMockDispatcher dispatcher, final BmpMockArguments arguments) {
import java.net.InetSocketAddress;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
-import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import net.sourceforge.argparse4j.inf.ArgumentType;
import net.sourceforge.argparse4j.inf.Namespace;
import org.opendaylight.protocol.util.ArgumentsInput;
parser.addArgument(toArgName(PRE_POLICY_ROUTES_COUNT_DST)).type(Integer.class).setDefault(0);
parser.addArgument(toArgName(POST_POLICY_ROUTES_COUNT_DST)).type(Integer.class).setDefault(0);
parser.addArgument(toArgName(PASSIVE_MODE_DST)).action(Arguments.storeTrue());
- parser.addArgument(toArgName(LOCAL_ADDRESS_DST)).type(new ArgumentType<InetSocketAddress>() {
- @Override
- public InetSocketAddress convert(final ArgumentParser parser, final Argument arg, final String value)
- throws ArgumentParserException {
- return getInetSocketAddress(value, DEFAULT_LOCAL_PORT);
- }
- }).setDefault(LOCAL_ADDRESS);
- parser.addArgument(toArgName(REMOTE_ADDRESS_DST)).type(new ArgumentType<InetSocketAddress>() {
- @Override
- public InetSocketAddress convert(final ArgumentParser parser, final Argument arg, final String value)
- throws ArgumentParserException {
- return getInetSocketAddress(value, DEFAULT_REMOTE_PORT);
- }
- }).setDefault(REMOTE_ADDRESS);
- parser.addArgument(toArgName(LOG_LEVEL_DST)).type(new ArgumentType<Level>(){
- @Override
- public Level convert(final ArgumentParser parser, final Argument arg, final String value) throws ArgumentParserException {
- return Level.toLevel(value);
- }}).setDefault(Level.INFO);
+ parser.addArgument(toArgName(LOCAL_ADDRESS_DST)).type((parser13, arg, value) -> getInetSocketAddress(value, DEFAULT_LOCAL_PORT)).setDefault(LOCAL_ADDRESS);
+ parser.addArgument(toArgName(REMOTE_ADDRESS_DST)).type((parser12, arg, value) -> getInetSocketAddress(value, DEFAULT_REMOTE_PORT)).setDefault(REMOTE_ADDRESS);
+ parser.addArgument(toArgName(LOG_LEVEL_DST)).type((parser1, arg, value) -> Level.toLevel(value)).setDefault(Level.INFO);
return parser;
}
import static org.opendaylight.protocol.util.Ipv4Util.incrementIpv4Prefix;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@Override
public void channelActive(final ChannelHandlerContext ctx) {
this.channel = ctx.channel();
- this.channel.closeFuture().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture future) throws Exception {
- LOG.info("BMP session {} final successfully established.", BmpMockSession.this.channel);
- }
- });
+ this.channel.closeFuture().addListener((ChannelFutureListener) future -> LOG.info("BMP session {} final successfully established.", BmpMockSession.this.channel));
LOG.info("BMP session {} successfully established.", this.channel);
final InetSocketAddress localAddress = (InetSocketAddress) this.channel.localAddress();
this.remoteAddress = (InetSocketAddress) this.channel.remoteAddress();
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.util.InetSocketAddressUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.InitiationMessage;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.PeerUp;
Mockito.doReturn(LOCAL_ADDRESS).when(this.channel).localAddress();
final ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class);
Mockito.doReturn(pipeline).when(this.channel).pipeline();
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- messages.add((Notification) invocation.getArguments()[0]);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ messages.add((Notification) invocation.getArguments()[0]);
+ return null;
}).when(this.channel).writeAndFlush(Mockito.any());
final ChannelFuture channelFuture = Mockito.mock(ChannelFuture.class);
Mockito.doReturn(null).when(channelFuture).addListener(Mockito.any());
if (peerDown.isLocalSystemClosed()) {
if (peerDown.getData() instanceof FsmEventCode) {
ByteBufWriteUtil.writeUnsignedByte(REASON_TWO.getValue(), buffer);
- ByteBufWriteUtil.writeUnsignedShort(((FsmEventCode) peerDown.getData()).getFsmEventCode().intValue(), buffer);
+ ByteBufWriteUtil.writeUnsignedShort(((FsmEventCode) peerDown.getData()).getFsmEventCode(), buffer);
} else if (peerDown.getData() instanceof
org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.peer.down.data.Notification) {
ByteBufWriteUtil.writeUnsignedByte(REASON_ONE.getValue(), buffer);
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.MultiExitDiscBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.OriginBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.OriginatorIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.UnrecognizedAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.aigp.AigpTlvBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.as.path.Segments;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.as.path.SegmentsBuilder;
.setMultiExitDisc(new MultiExitDiscBuilder().setMed(123L).build())
.setOrigin(new OriginBuilder().setValue(BgpOrigin.Igp).build())
.setOriginatorId(new OriginatorIdBuilder().setOriginator(IPV4_ADDRESS_12).build())
- .setUnrecognizedAttributes(new ArrayList<UnrecognizedAttributes>());
+ .setUnrecognizedAttributes(new ArrayList<>());
return attribBuilder.build();
}
private static final byte[] DATA = { 0, 1, 0, 4, 't', 'e', 's', 't' };
private static final int TYPE = 1;
- public static final BmpTlvSerializer DESCRIPTION_TLV_SERIALIZER = new BmpTlvSerializer() {
- @Override
- public void serializeTlv(final Tlv tlv, final ByteBuf output) {
- Preconditions.checkArgument(tlv instanceof DescriptionTlv, "DescriptionTlv is mandatory.");
- TlvUtil.formatTlvAscii(TYPE, ((DescriptionTlv) tlv).getDescription(), output);
- }
+ public static final BmpTlvSerializer DESCRIPTION_TLV_SERIALIZER = (tlv, output) -> {
+ Preconditions.checkArgument(tlv instanceof DescriptionTlv, "DescriptionTlv is mandatory.");
+ TlvUtil.formatTlvAscii(TYPE, ((DescriptionTlv) tlv).getDescription(), output);
};
- public static final BmpTlvParser DESCRIPTION_TLV_PARSER = new BmpTlvParser() {
- @Override
- public Tlv parseTlv(final ByteBuf buffer) throws BmpDeserializationException {
- if (buffer == null) {
- return null;
- }
- return new DescriptionTlvBuilder().setDescription(buffer.toString(StandardCharsets.US_ASCII)).build();
+ public static final BmpTlvParser DESCRIPTION_TLV_PARSER = buffer -> {
+ if (buffer == null) {
+ return null;
}
+ return new DescriptionTlvBuilder().setDescription(buffer.toString(StandardCharsets.US_ASCII)).build();
};
@Before
private static class SimpleAbstractBmpExtensionProviderActivator extends AbstractBmpExtensionProviderActivator {
@Override
protected List<AutoCloseable> startImpl(final BmpExtensionProviderContext context) {
- final List<AutoCloseable> reg = new ArrayList<AutoCloseable>();
+ final List<AutoCloseable> reg = new ArrayList<>();
reg.add(context.registerBmpMessageParser(1, new SimpleBmpMessageRegistry()));
return reg;
}
@Override
protected final Object doExecute() throws Exception {
final PrintStream out = this.session.getConsole();
- getObjectNames().forEach(objectName -> {
- onExecution(out, getRuntimeMXBean(objectName), objectName);
- });
+ getObjectNames().forEach(objectName -> onExecution(out, getRuntimeMXBean(objectName), objectName));
return null;
}
@Override
public EvpnChoice serializeEvpnModel(final ChoiceNode evpnChoice) {
- return getEvpnCase(evpnChoice, (serializer, cont) -> serializer.serializeEvpnModel(cont));
+ return getEvpnCase(evpnChoice, EvpnSerializer::serializeEvpnModel);
}
@Override
public EvpnChoice serializeEvpnRouteKey(final ChoiceNode evpnChoice) {
- return getEvpnCase(evpnChoice, (serializer, cont) -> serializer.createRouteKey(cont));
+ return getEvpnCase(evpnChoice, EvpnSerializer::createRouteKey);
}
private EvpnChoice getEvpnCase(final ChoiceNode evpnChoice, final SerializerInterface serializerInterface) {
protected final String stringNlri(final List<Flowspec> flows) {
final StringBuilder buffer = new StringBuilder("all packets ");
final Joiner joiner = Joiner.on(FLOW_SEPARATOR);
- joiner.appendTo(buffer, Iterables.transform(flows, fs -> encodeFlow(fs)));
+ joiner.appendTo(buffer, Iterables.transform(flows, this::encodeFlow));
return buffer.toString().replace(" ", " ");
}
"The extended community %s is not TrafficMarkingExtendedCommunity type.", extendedCommunity);
final TrafficMarkingExtendedCommunity trafficMarking = ((org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev150807.TrafficMarkingExtendedCommunity) extendedCommunity).getTrafficMarkingExtendedCommunity();
byteAggregator.writeZero(RESERVED);
- ByteBufWriteUtil.writeUnsignedByte(trafficMarking.getGlobalAdministrator().getValue().shortValue(), byteAggregator);
+ ByteBufWriteUtil.writeUnsignedByte(trafficMarking.getGlobalAdministrator().getValue(), byteAggregator);
}
@Override
private FlowspecType createLabel() {
final List<FlowLabel> labels = Lists.newArrayList();
- labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, false, true, false, false)).setValue(new Long(16777222L)).build());
- labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, true, true, false, false)).setValue(new Long(258L)).build());
+ labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, false, true, false, false)).setValue(16777222L).build());
+ labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, true, true, false, false)).setValue(258L).build());
return new FlowLabelCaseBuilder().setFlowLabel(labels).build();
}
private FlowspecType createLabel() {
final List<FlowLabel> labels = Lists.newArrayList();
- labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, false, true, false, false)).setValue(new Long(16777222L)).build());
- labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, true, true, false, false)).setValue(new Long(258L)).build());
+ labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, false, true, false, false)).setValue(16777222L).build());
+ labels.add(new FlowLabelBuilder().setOp(new NumericOperand(false, true, true, false, false)).setValue(258L).build());
return new FlowLabelCaseBuilder().setFlowLabel(labels).build();
}
import org.opendaylight.protocol.bgp.inet.codec.Ipv6BgpPrefixSidParser;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.attributes.bgp.prefix.sid.bgp.prefix.sid.tlvs.bgp.prefix.sid.tlv.Ipv6SidTlvBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.bgp.prefix.sid.bgp.prefix.sid.tlvs.BgpPrefixSidTlv;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
public final class Ipv6BgpPrefixSidParserTest {
@Test(expected=IllegalArgumentException.class)
public void testWrongTlvType() {
- this.handler.serializeBgpPrefixSidTlv(new BgpPrefixSidTlv() {
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return BgpPrefixSidTlv.class;
- }
- }, Unpooled.EMPTY_BUFFER);
+ this.handler.serializeBgpPrefixSidTlv(() -> BgpPrefixSidTlv.class, Unpooled.EMPTY_BUFFER);
}
@Test
assertNull(message.getNlri());
// attributes
- final List<AsNumber> asNumbers = new ArrayList<AsNumber>();
+ final List<AsNumber> asNumbers = new ArrayList<>();
asNumbers.add(new AsNumber(65001L));
final List<Segments> asPath = Lists.newArrayList();
asPath.add(new SegmentsBuilder().setAsSequence(asNumbers).build());
new DestinationIpv4Builder().setIpv4Prefixes(this.prefixes).build()).build();
this.ip4caseAD = new DestinationIpv4CaseBuilder().setDestinationIpv4(new DestinationIpv4Builder().setIpv4Prefixes(this.prefixes).build()).build();
- final ArrayList<Ipv4Prefixes> fakePrefixes = new ArrayList<Ipv4Prefixes>(this.prefixes);
+ final ArrayList<Ipv4Prefixes> fakePrefixes = new ArrayList<>(this.prefixes);
fakePrefixes.add(new Ipv4PrefixesBuilder().setPrefix(wrongPrefix).build());
this.ip4caseWDWrong = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.DestinationIpv4CaseBuilder().setDestinationIpv4(
new DestinationIpv4Builder().setIpv4Prefixes(fakePrefixes).build()).build();
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv6NextHopCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.ipv4.next.hop._case.Ipv4NextHopBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.ipv6.next.hop._case.Ipv6NextHopBuilder;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
public class NextHopParserSerializerTest {
public void testSerializeIpv4NextHopEmpty() {
buffer.clear();
try {
- ipv4NextHopParserSerializer.serializeNextHop(new CNextHop() {
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return null;
- }
- }, buffer);
+ ipv4NextHopParserSerializer.serializeNextHop(() -> null, buffer);
} catch (final IllegalArgumentException e) {
assertEquals("cNextHop is not a Ipv4 NextHop object.", e.getMessage());
}
public void testSerializeIpv6NextHopEmpty() {
buffer.clear();
try {
- ipv6NextHopParserSerializer.serializeNextHop(new CNextHop() {
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return null;
- }
- }, buffer);
+ ipv6NextHopParserSerializer.serializeNextHop(() -> null, buffer);
} catch (final IllegalArgumentException e) {
assertEquals("cNextHop is not a Ipv6 NextHop object.", e.getMessage());
}
private static List<SrgbValue> parseSrgbs(final ByteBuf buffer) {
Preconditions.checkState(buffer.readableBytes() % SRGB_LENGTH == 0, "Number of SRGBs doesn't fit available bytes.");
- final List<SrgbValue> ret = new ArrayList<SrgbValue>();
+ final List<SrgbValue> ret = new ArrayList<>();
while (buffer.isReadable()) {
ret.add(new SrgbValueBuilder().setBase(new Srgb((long) buffer.readUnsignedMedium())).setRange(new Srgb((long) buffer.readUnsignedMedium())).build());
}
@Test
public void testOriginatorParser() {
final OriginatorSrgbTlvParser parser = new OriginatorSrgbTlvParser();
- final List<SrgbValue> list = new ArrayList<SrgbValue>();
+ final List<SrgbValue> list = new ArrayList<>();
final Srgb srgb1 = new Srgb(1L);
final Srgb srgb2 = new Srgb(2L);
@Override
public <T extends DataObject> void registerBGPConfigHolder(final Class<T> clazz) {
- configHolderMap.put(clazz, new BGPConfigHolderImpl<T>(OpenConfigComparatorFactory.getComparator(clazz)));
+ configHolderMap.put(clazz, new BGPConfigHolderImpl<>(OpenConfigComparatorFactory.getComparator(clazz)));
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.services.service.Instance;
import org.opendaylight.yangtools.yang.binding.ChildOf;
+@SuppressWarnings("ALL")
final class AddPathFunction {
private AddPathFunction() {
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressWarnings("ALL")
final class BGPAppPeerProvider {
private static final String APPLICATION_RIB = "application-rib_";
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressWarnings("ALL")
final class BGPPeerProvider {
private static final String PEER = "peer_";
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressWarnings("ALL")
final class BGPRibImplProvider {
private static final Logger LOG = LoggerFactory.getLogger(BGPRibImplProvider.class);
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.dom.rev131028.DomAsyncDataBroker;
import org.opendaylight.yangtools.yang.binding.ChildOf;
+@SuppressWarnings("ALL")
public final class DataBrokerFunction {
private DataBrokerFunction() {
throw new UnsupportedOperationException();
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.services.service.Instance;
import org.opendaylight.yangtools.yang.binding.ChildOf;
+@SuppressWarnings("ALL")
final class PathSelectionModeFunction {
private static final Map<String, Class<? extends ModuleType>> PATH_SELECTION_MODULE_TYPES;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.services.service.Instance;
import org.opendaylight.yangtools.yang.binding.ChildOf;
+@SuppressWarnings("ALL")
final class RibInstanceFunction {
private RibInstanceFunction() {
throw new UnsupportedOperationException();
import com.google.common.base.Function;
import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.services.service.Instance;
import org.opendaylight.yangtools.yang.binding.ChildOf;
+@SuppressWarnings("ALL")
final class TableTypesFunction {
private TableTypesFunction() {
throw new UnsupportedOperationException();
}
final ImmutableList<Module> modules = FluentIterable.from(maybeModules)
- .filter(new Predicate<Optional<Module>>() {
- @Override
- public boolean apply(final Optional<Module> input) {
- return input.isPresent();
- }
- }).transform(new Function<Optional<Module>, Module>() {
- @Override
- public Module apply(final Optional<Module> input) {
- return input.get();
- }
- }).toList();
+ .filter(Optional::isPresent).transform(Optional::get).toList();
return toServices(function, afiSafis, afiSafiToModuleName(afiSafis, modules), moduleNameToService);
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.ModuleKey;
public class BGPConfigHolderImplTest {
- private static final BGPConfigHolderImpl<Bgp> HOLDER = new BGPConfigHolderImpl<Bgp>(OpenConfigComparatorFactory.getComparator(Bgp.class));
+ private static final BGPConfigHolderImpl<Bgp> HOLDER = new BGPConfigHolderImpl<>(OpenConfigComparatorFactory.getComparator(Bgp.class));
@Test
public void test() {
final Global global = Mockito.mock(Global.class);
final Neighbors neighbors = Mockito.mock(Neighbors.class);
- final ArrayList<Neighbor> neighbor = new ArrayList<Neighbor>();
+ final ArrayList<Neighbor> neighbor = new ArrayList<>();
neighbor.add(createNeighbor());
Mockito.doReturn(neighbor).when(neighbors).getNeighbor();
Mockito.doReturn(neighbors).when(this.modif1).getDataAfter();
}
private Neighbor createNeighbor() {
- final List<AfiSafi> families = new ArrayList<AfiSafi>();
+ final List<AfiSafi> families = new ArrayList<>();
final AfiSafi afi = new AfiSafiBuilder().build();
families.add(afi);
return new NeighborBuilder()
private Bgp createBgp() {
final GlobalBuilder global = new GlobalBuilder();
- final List<AfiSafi> families = new ArrayList<AfiSafi>();
+ final List<AfiSafi> families = new ArrayList<>();
global.setAfiSafis(new AfiSafisBuilder().setAfiSafi(families).build())
.setConfig(new ConfigBuilder()
.setRouterId(new Ipv4Address("1.1.1.1"))
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@SuppressWarnings("ALL")
public class AbstractBGPOpenConfigMapperTest {
private static final InstanceConfigurationIdentifier IDENTIFIER = new InstanceConfigurationIdentifier("instanceName");
@Override
public void parseAttribute(final ByteBuf buffer, final AttributesBuilder builder) throws BGPDocumentedException, BGPParsingException {
final BgpPrefixSidBuilder sid = new BgpPrefixSidBuilder();
- final List<BgpPrefixSidTlvs> tlvList = new ArrayList<BgpPrefixSidTlvs>();
+ final List<BgpPrefixSidTlvs> tlvList = new ArrayList<>();
while (buffer.isReadable()) {
final BgpPrefixSidTlv tlv = this.reg.parseBgpPrefixSidTlv(buffer.readUnsignedByte(), buffer);
tlvList.add(new BgpPrefixSidTlvsBuilder().setBgpPrefixSidTlv(tlv).build());
@Test
public void testCapabilityHandler() throws BGPDocumentedException, BGPParsingException {
- final List<AddressFamilies> family = new ArrayList<AddressFamilies>();
+ final List<AddressFamilies> family = new ArrayList<>();
family.add(new AddressFamiliesBuilder().setAfi(this.afi).setSafi(this.safi).setSendReceive(SendReceive.forValue(1)).build());
final CParameters capabilityToSerialize = new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
@Test
public void testSendReceiveIgnored() throws BGPDocumentedException, BGPParsingException {
final CParameters capabilityToSerialize = new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
- new AddPathCapabilityBuilder().setAddressFamilies(new ArrayList<AddressFamilies>()).build()).build()).build();
+ new AddPathCapabilityBuilder().setAddressFamilies(new ArrayList<>()).build()).build()).build();
final ByteBuf bytes = this.parseWrongBytes.copy();
final AddPathCapabilityHandler handler = new AddPathCapabilityHandler(this.afiRegistry, this.safiRegistry);
@Test(expected=IllegalArgumentException.class)
public void testUnhandledAfi() {
- final List<AddressFamilies> family = new ArrayList<AddressFamilies>();
+ final List<AddressFamilies> family = new ArrayList<>();
family.add(new AddressFamiliesBuilder().setAfi(this.afi).setSafi(this.safi).setSendReceive(SendReceive.forValue(2)).build());
final CParameters capabilityToSerialize = new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
@Test(expected=IllegalArgumentException.class)
public void testUnhandledSafi() {
- final List<AddressFamilies> family = new ArrayList<AddressFamilies>();
+ final List<AddressFamilies> family = new ArrayList<>();
family.add(new AddressFamiliesBuilder().setAfi(this.afi).setSafi(this.safi).setSendReceive(SendReceive.forValue(3)).build());
final CParameters capabilityToSerialize = new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
@Test(expected=IllegalArgumentException.class)
public void testUnhandledSendReceive() {
- final List<AddressFamilies> family = new ArrayList<AddressFamilies>();
+ final List<AddressFamilies> family = new ArrayList<>();
family.add(new AddressFamiliesBuilder().setAfi(this.afi).setSafi(this.safi).setSendReceive(SendReceive.forValue(4)).build());
final CParameters capabilityToSerialize = new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
/**
* Used by other tests as well
*/
- static final List<byte[]> inputBytes = new ArrayList<byte[]>();
+ static final List<byte[]> inputBytes = new ArrayList<>();
private static final int COUNTER = 7;
assertNull(message.getWithdrawnRoutes());
// attributes
- final List<AsNumber> asNumbers = new ArrayList<AsNumber>();
+ final List<AsNumber> asNumbers = new ArrayList<>();
asNumbers.add(new AsNumber(65002L));
final List<Segments> asPath = Lists.newArrayList();
asPath.add(new SegmentsBuilder().setAsSequence(asNumbers).build());
assertNull(message.getWithdrawnRoutes());
// attributes
- final List<AsNumber> asNumbers = new ArrayList<AsNumber>();
+ final List<AsNumber> asNumbers = new ArrayList<>();
asNumbers.add(new AsNumber(30L));
final List<Segments> asPath = Lists.newArrayList();
asPath.add(new SegmentsBuilder().setAsSequence(asNumbers).build());
private final HandlerRegistry<DataContainer, AttributeParser, AttributeSerializer> handlers = new HandlerRegistry<>();
private final Map<AbstractRegistration, AttributeSerializer> serializers = new LinkedHashMap<>();
private final AtomicReference<Iterable<AttributeSerializer>> roSerializers =
- new AtomicReference<Iterable<AttributeSerializer>>(this.serializers.values());
+ new AtomicReference<>(this.serializers.values());
private final List<UnrecognizedAttributes> unrecognizedAttributes = new ArrayList<>();
this.maximumCachedObjects = maximumCachedObjects;
final Cache<Object, Object> cache = CacheBuilder.newBuilder().maximumSize(maximumCachedObjects).build();
- this.cacheRef = new AtomicReference<Cache<Object,Object>>(cache);
+ this.cacheRef = new AtomicReference<>(cache);
}
@Override
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.bgp.prefix.sid.bgp.prefix.sid.tlvs.BgpPrefixSidTlv;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
public class SimpleRegistryTest {
- private static final MultiPathSupport ADD_PATH_SUPPORT = new MultiPathSupport() {
- @Override
- public boolean isTableTypeSupported(final BgpTableType tableType) {
- return true;
- }
- };
+ private static final MultiPathSupport ADD_PATH_SUPPORT = tableType -> true;
private static final PeerSpecificParserConstraint CONSTRAINT = new PeerSpecificParserConstraint() {
@Override
final List<UnrecognizedAttributes> unrecogAttribs = simpleAttrReg.parseAttributes(Unpooled.wrappedBuffer(attributeBytes)).getUnrecognizedAttributes();
assertEquals(UNRECOGNIZED_ATTRIBUTE_COUNT, unrecogAttribs.size());
final UnrecognizedAttributes unrecogAttrib = unrecogAttribs.get(FIRST_ATTRIBUTE);
- final UnrecognizedAttributesKey expectedAttribKey = new UnrecognizedAttributesKey(unrecogAttrib.getType().shortValue());
+ final UnrecognizedAttributesKey expectedAttribKey = new UnrecognizedAttributesKey(unrecogAttrib.getType());
assertTrue(unrecogAttrib.isPartial());
assertTrue(unrecogAttrib.isTransitive());
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import javax.annotation.concurrent.NotThreadSafe;
import org.opendaylight.protocol.bgp.mode.api.BestPathState;
public BestPathStateImpl(final ContainerNode attributes) {
final NamespaceSpecificIds col;
try {
- col = PATH_CACHE.get(attributes.getNodeType().getModule(), new Callable<NamespaceSpecificIds>() {
- @Override
- public NamespaceSpecificIds call() {
- return new NamespaceSpecificIds(attributes.getNodeType());
- }
- });
+ col = PATH_CACHE.get(attributes.getNodeType().getModule(), () -> new NamespaceSpecificIds(attributes.getNodeType()));
} catch (final ExecutionException e) {
LOG.error("Error creating namespace-specific attributes collection.", e);
throw new IllegalStateException("Error creating namespace-specific attributes collection.", e);
<type>test-jar</type>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>testtool-util</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
private Map<TablesKey, PathSelectionMode> mapBestPathSelectionStrategyByFamily(final List<BGPBestPathSelection> bestPathSelectionDependency) {
return Collections.unmodifiableMap(bestPathSelectionDependency.stream().collect(
- Collectors.toMap(st -> new TablesKey(st.getAfi(), st.getSafi()), st -> st.getStrategy())));
+ Collectors.toMap(st -> new TablesKey(st.getAfi(), st.getSafi()), BGPBestPathSelection::getStrategy)));
}
private static interface AutoCloseableRIB extends RIB, AutoCloseable {
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
if (this.state != State.FINISHED) {
this.state = State.OPEN_SENT;
- this.pending = this.channel.eventLoop().schedule(new Runnable() {
- @Override
- public void run() {
- synchronized (AbstractBGPSessionNegotiator.this) {
- AbstractBGPSessionNegotiator.this.pending = null;
- if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
- AbstractBGPSessionNegotiator.this
- .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
- negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
- AbstractBGPSessionNegotiator.this.state = State.FINISHED;
- }
+ this.pending = this.channel.eventLoop().schedule(() -> {
+ synchronized (AbstractBGPSessionNegotiator.this) {
+ AbstractBGPSessionNegotiator.this.pending = null;
+ if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
+ AbstractBGPSessionNegotiator.this
+ .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
+ negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
+ AbstractBGPSessionNegotiator.this.state = State.FINISHED;
}
}
}, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
}
private void sendMessage(final Notification msg) {
- this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture f) {
- if (!f.isSuccess()) {
- LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel, f.cause());
- negotiationFailedCloseChannel(f.cause());
- } else {
- LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
- }
+ this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
+ if (!f.isSuccess()) {
+ LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel, f.cause());
+ negotiationFailedCloseChannel(f.cause());
+ } else {
+ LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
}
});
}
public Future<RpcResult<Void>> routeRefreshRequest(final RouteRefreshRequestInput input) {
final ChannelFuture f = sendRRMessage(input);
if (f != null) {
- return Futures.transform(JdkFutureAdapters.listenInPoolThread(f), new Function<Void, RpcResult<Void>>() {
- @Override
- public RpcResult<Void> apply(final Void input) {
- if (f.isSuccess()) {
- return RpcResultBuilder.<Void>success().build();
- } else {
- return RpcResultBuilder.<Void>failed().withError(ErrorType.RPC, FAILURE_MSG).build();
- }
+ return Futures.transform(JdkFutureAdapters.listenInPoolThread(f), (Function<Void, RpcResult<Void>>) input1 -> {
+ if (f.isSuccess()) {
+ return RpcResultBuilder.<Void>success().build();
+ } else {
+ return RpcResultBuilder.<Void>failed().withError(ErrorType.RPC, FAILURE_MSG).build();
}
});
}
final BGPProtocolSessionPromise lock = this;
try {
- LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(CONNECT_TIMEOUT));
+ LOG.debug("Promise {} attempting connect for {}ms", lock, CONNECT_TIMEOUT);
if (this.address.isUnresolved()) {
this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
}
InstanceType(final String beanName, final List<Class<?>> services) {
this.beanName = beanName;
this.services = new String[services.size()];
- services.stream().map(clazz -> clazz.getName()).collect(Collectors.toList()).toArray(this.services);
+ services.stream().map(Class::getName).collect(Collectors.toList()).toArray(this.services);
}
public String getBeanName() {
}
public final synchronized void init(@Nonnull Set<TablesKey> tablesKeySet) {
- tablesKeySet.stream().forEach(tablesKey -> init(tablesKey));
+ tablesKeySet.stream().forEach(this::init);
}
public final synchronized UnsignedInt32Counter init(@Nonnull final TablesKey tablesKey) {
public final void resetAll() {
LOG.debug("Resetting all route counters..");
- this.counters.values().stream().forEach(v -> v.resetCount());
+ this.counters.values().stream().forEach(UnsignedInt32Counter::resetCount);
}
}
mxBean2.setAddressFamily(AddPathImplModuleTest.createAddressFamily(transaction, "add-path-inst-2"));
mxBean2.setSendReceive(SendReceive.Receive);
- final List<ObjectName> ret = new ArrayList<ObjectName>();
+ final List<ObjectName> ret = new ArrayList<>();
ret.add(name1);
ret.add(name2);
return ret;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
final ChannelFuture f = mock(ChannelFuture.class);
doReturn(null).when(f).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) {
- final Object[] args = invocation.getArguments();
- BGPSessionImplTest.this.receivedMsgs.add((Notification) args[0]);
- return f;
- }
+ doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ BGPSessionImplTest.this.receivedMsgs.add((Notification) args[0]);
+ return f;
}).when(this.speakerListener).writeAndFlush(Mockito.any(Notification.class));
doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
doReturn(true).when(this.speakerListener).isActive();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable command = (Runnable) invocation.getArguments()[0];
- final long delay = (long) invocation.getArguments()[1];
- final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
- GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
- return null;
- }
+ doAnswer(invocation -> {
+ final Runnable command = (Runnable) invocation.getArguments()[0];
+ final long delay = (long) invocation.getArguments()[1];
+ final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
+ GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
+ return null;
}).when(this.eventLoop).schedule(Mockito.any(Runnable.class), Mockito.any(long.class), Mockito.any(TimeUnit.class));
doReturn("TestingChannel").when(this.speakerListener).toString();
doReturn(true).when(this.speakerListener).isWritable();
assertEquals(BGP_ID.getValue(), state.getLocalPeerPreferences().getBgpId().getValue());
assertEquals(1, state.getLocalPeerPreferences().getAdvertizedTableTypes().size());
assertEquals(HOLD_TIMER, state.getLocalPeerPreferences().getHoldtimer().intValue());
- assertTrue(state.getLocalPeerPreferences().getFourOctetAsCapability().booleanValue());
- assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability().booleanValue());
+ assertTrue(state.getLocalPeerPreferences().getFourOctetAsCapability());
+ assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability());
assertTrue(state.getLocalPeerPreferences().getGrCapability());
assertEquals(LOCAL_IP, new String(state.getRemotePeerPreferences().getHost().getValue()));
assertEquals(LOCAL_PORT, state.getRemotePeerPreferences().getPort().getValue().intValue());
public class BgpPeerRpcTest {
- private final Set<TablesKey> supportedFamilies = new HashSet<TablesKey>();
+ private final Set<TablesKey> supportedFamilies = new HashSet<>();
private final BGPSessionImpl session = Mockito.mock(BGPSessionImpl.class);
private final BgpPeerRpc rpc = new BgpPeerRpc(this.session, this.supportedFamilies);
private final PeerRef peer = Mockito.mock(PeerRef.class);
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
doReturn(null).when(f).addListener(any(GenericFutureListener.class));
final InetAddress peerAddress = InetAddress.getByName("1.1.1.2");
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) {
- final Object[] args = invocation.getArguments();
- FSMTest.this.receivedMsgs.add((Notification) args[0]);
- return f;
- }
+ doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ FSMTest.this.receivedMsgs.add((Notification) args[0]);
+ return f;
}).when(this.speakerListener).writeAndFlush(any(Notification.class));
doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
doReturn(null).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
final BGPPeerRegistry peerRegistry = new StrictBGPPeerRegistry();
peerRegistry.addPeer(new IpAddress(new Ipv4Address(peerAddress.getHostAddress())), new SimpleSessionListener(), prefs);
- this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE), this.speakerListener, peerRegistry);
+ this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.speakerListener, peerRegistry);
this.classicOpen = new OpenBuilder().setMyAsNumber(30).setHoldTimer(3).setVersion(new ProtocolVersion((short) 4)).setBgpParameters(
tlvs).setBgpIdentifier(new Ipv4Address("1.1.1.2")).build();
@Test
public void testDenyPeer() {
- this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE), this.speakerListener, new StrictBGPPeerRegistry());
+ this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.speakerListener, new StrictBGPPeerRegistry());
this.clientSession.channelActive(null);
assertEquals(1, this.receivedMsgs.size());
assertTrue(this.receivedMsgs.get(0) instanceof Notify);
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
+@SuppressWarnings("ALL")
public class PeerTest extends AbstractRIBTestSetup {
private ApplicationPeer peer;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
doReturn(null).when(mock(ChannelFuture.class)).addListener(any());
doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
doReturn(true).when(this.speakerListener).isActive();
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable command = (Runnable) invocation.getArguments()[0];
- final long delay = (long) invocation.getArguments()[1];
- final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
- GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
- return null;
- }
+ doAnswer(invocation -> {
+ final Runnable command = (Runnable) invocation.getArguments()[0];
+ final long delay = (long) invocation.getArguments()[1];
+ final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
+ GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
+ return null;
}).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
doReturn("TestingChannel").when(this.speakerListener).toString();
doReturn(true).when(this.speakerListener).isWritable();
any(YangInstanceIdentifier.class), any(NormalizedNode.class));
Mockito.doNothing().when(this.tx).delete(Mockito.any(LogicalDatastoreType.class), Mockito.any(YangInstanceIdentifier.class));
final CheckedFuture future = mock(CheckedFuture.class);
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(future).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
Mockito.doReturn(future).when(this.tx).submit();
Mockito.doReturn(mock(Optional.class)).when(future).checkedGet();
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
Mockito.doNothing().when(this.domDW).delete(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class));
Mockito.doNothing().when(this.domDW).merge(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class), any(NormalizedNode.class));
final CheckedFuture checkedFuture = mock(CheckedFuture.class);
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(checkedFuture).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
Mockito.doReturn(checkedFuture).when(this.domDW).submit();
Mockito.doReturn(null).when(checkedFuture).checkedGet();
Mockito.verify(this.render).getConfiguredPeerCounter();
Mockito.verify(this.configurationWriter).apply();
Mockito.verify(this.bgpPeerRegistry).addPeer(any(), any(), any());
- Mockito.verify(this.dispatcher).createReconnectingClient(any(InetSocketAddress.class), any(BGPPeerRegistry.class), anyInt(), any(Optional.class));
+ Mockito.verify(this.dispatcher).createReconnectingClient(any(InetSocketAddress.class),
+ any(BGPPeerRegistry.class), anyInt(), any(Optional.class));
try {
this.bgpPeer.start(this.rib, neighbor, this.mappingService, this.configurationWriter);
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.mode.impl.add.all.paths.AllPathSelection;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenConfigMappingService;
@Before
public void setUp() throws Exception {
super.setUp();
- Mockito.doAnswer(new Answer<ClusterSingletonServiceRegistration>() {
- @Override
- public ClusterSingletonServiceRegistration answer(final InvocationOnMock invocationOnMock) throws Throwable {
- RibImplTest.this.singletonService = (ClusterSingletonService) invocationOnMock.getArguments()[0];
- return RibImplTest.this.singletonServiceRegistration;
- }
+ Mockito.doAnswer(invocationOnMock -> {
+ RibImplTest.this.singletonService = (ClusterSingletonService) invocationOnMock.getArguments()[0];
+ return RibImplTest.this.singletonServiceRegistration;
}).when(this.clusterSingletonServiceProvider).registerClusterSingletonService(any(ClusterSingletonService.class));
Mockito.doReturn(Collections.singletonMap(TABLE_TYPE, new AllPathSelection()))
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- AbstractRIBSupportTest.this.insertedRoutes.add(mappingService.fromNormalizedNode((YangInstanceIdentifier) args[1], (NormalizedNode<?, ?>) args[2]));
- return args[1];
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ AbstractRIBSupportTest.this.insertedRoutes.add(AbstractRIBSupportTest.this.mappingService.fromNormalizedNode((YangInstanceIdentifier) args[1], (NormalizedNode<?, ?>) args[2]));
+ return args[1];
}).when(this.tx).put(Mockito.any(LogicalDatastoreType.class), Mockito.any(YangInstanceIdentifier.class), Mockito.any(NormalizedNode.class));
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- AbstractRIBSupportTest.this.deletedRoutes.add(mappingService.fromYangInstanceIdentifier((YangInstanceIdentifier) args[1]));
- return args[1];
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ AbstractRIBSupportTest.this.deletedRoutes.add(AbstractRIBSupportTest.this.mappingService.fromYangInstanceIdentifier((YangInstanceIdentifier) args[1]));
+ return args[1];
}).when(this.tx).delete(Mockito.any(LogicalDatastoreType.class), Mockito.any(YangInstanceIdentifier.class));
this.deletedRoutes = new ArrayList<>();
this.insertedRoutes = new ArrayList<>();
}
// Re-generate termination points
- this.nb.setTerminationPoint(Lists.newArrayList(Collections2.transform(this.tps.values(), input -> input.getTp())));
+ this.nb.setTerminationPoint(Lists.newArrayList(Collections2.transform(this.tps.values(), TpHolder::getTp)));
// Re-generate prefixes
this.inab.setPrefix(Lists.newArrayList(this.prefixes.values()));
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
import org.osgi.framework.BundleContext;
+@SuppressWarnings("ALL")
public final class BackwardsCssTopologyProvider {
public static TopologyReferenceSingletonService createBackwardsCssInstance(final TopologyTypes topologyTypes, final TopologyId topologyId, final DataBroker dataBroker, final BundleContext bundleContext,
final UriBuilder c = new UriBuilder(b, "foo");
assertEquals("bgpls://1:Direct:10/type=foo", c.toString());
- a.add("foo", new Long(25L));
+ a.add("foo", 25L);
assertEquals("bgpls://Direct:10/&foo=25", a.toString());
final LinkCaseBuilder linkB = new LinkCaseBuilder();
import org.opendaylight.yangtools.concepts.AbstractRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@SuppressWarnings("ALL")
public class Ipv4ReachabilityTopologyBuilderModuleTest extends AbstractRIBImplModuleTest {
private static final String FACTORY_NAME = Ipv4ReachabilityTopologyBuilderModuleFactory.NAME;
import org.opendaylight.yangtools.concepts.AbstractRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@SuppressWarnings("ALL")
public class Ipv6ReachabilityTopologyBuilderModuleTest extends AbstractRIBImplModuleTest {
private static final String FACTORY_NAME = Ipv6ReachabilityTopologyBuilderModuleFactory.NAME;
import org.opendaylight.yangtools.concepts.AbstractRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+@SuppressWarnings("ALL")
public class LinkstateTopologyBuilderModuleTest extends AbstractRIBImplModuleTest {
private static final String FACTORY_NAME = LinkstateTopologyBuilderModuleFactory.NAME;
@Test
public void testHashCode() {
- final Set<Bandwidth> set = new HashSet<Bandwidth>();
+ final Set<Bandwidth> set = new HashSet<>();
set.add(this.b1);
assertEquals(1, set.size());
assertEquals(Integer.valueOf(22), registry.get("second"));
- registry.register(Character.valueOf('c'), 5);
+ registry.register('c', 5);
assertEquals(Integer.valueOf(5), registry.get('c'));
final MultiRegistry<Object, Number> registry = new MultiRegistry<>();
final String first = "first";
- registry.register(first, new Integer(1));
- assertEquals(Integer.valueOf(1), registry.get("first"));
+ registry.register(first, 1);
+ assertEquals(1, registry.get("first"));
- registry.register(first, new Short((short) 1));
- assertEquals(Integer.valueOf(1), registry.get("first"));
+ registry.register(first, (short) 1);
+ assertEquals(1, registry.get("first"));
- registry.register(first, new Short((short) 2));
- assertEquals(Integer.valueOf(1), registry.get("first"));
+ registry.register(first, (short) 2);
+ assertEquals(1, registry.get("first"));
}
@Test
final String first = "first";
final String second = "second";
- registry.register(first, new Integer(1));
- assertEquals(Integer.valueOf(1), registry.get("first"));
+ registry.register(first, 1);
+ assertEquals(1, registry.get("first"));
- registry.register(first, new Character('1'));
- assertEquals(Integer.valueOf(1), registry.get("first"));
+ registry.register(first, '1');
+ assertEquals(1, registry.get("first"));
- registry.register(second, new Character('2'));
- assertEquals(Character.valueOf('2'), registry.get("second"));
+ registry.register(second, '2');
+ assertEquals('2', registry.get("second"));
- registry.register(second, new Integer(2));
- assertEquals(Character.valueOf('2'), registry.get("second"));
+ registry.register(second, 2);
+ assertEquals('2', registry.get("second"));
registry.register(second, new Object());
- assertEquals(Character.valueOf('2'), registry.get("second"));
+ assertEquals('2', registry.get("second"));
}
}
final InstanceIdentifier<Topology> topoIId = InstanceIdentifier.builder(NetworkTopology.class)
.child(Topology.class, new TopologyKey(new TopologyId(getTopologyName()))).build();
final ListenerRegistration<TopologyDataChangeCounter> registration = getDataProviderDependency().registerDataTreeChangeListener(
- new DataTreeIdentifier<Topology>(LogicalDatastoreType.OPERATIONAL, topoIId), counter);
+ new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, topoIId), counter);
return new DataChangeCounterCloseable(counter, registration);
}
@Override
public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- final java.util.Set<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>> serviceIfcs2 = new java.util.HashSet<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>>();
+ final java.util.Set<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>> serviceIfcs2 = new java.util.HashSet<>();
return java.util.Collections.unmodifiableSet(serviceIfcs2);
}
final LspIdentifiers identifier = new LspIdentifiersBuilder().setAddressFamily(afiLsp).setLspId(lspId).setTunnelId(tunnelId).build();
final Lsp lsp = new LspBuilder().setPlspId(new PlspId(1L)).setTlvs(new TlvsBuilder().setLspIdentifiers(identifier).build()).build();
final Ero ero = new EroBuilder().build();
- final List<Object> objects = Lists.<Object>newArrayList(lsp, ero, bw);
+ final List<Object> objects = Lists.newArrayList(lsp, ero, bw);
final Reports validReports = codec.getValidReports(objects, Collections.emptyList());
assertNotNull(validReports.getPath().getBandwidth().getAugmentation(Bandwidth1.class));
assertTrue(objects.isEmpty());
} else if (obj instanceof Rp) {
final Rp o = (Rp) obj;
if (o.isProcessingRule()) {
- errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.absent()));
return null;
}
requestParameters.add(new RpsBuilder().setRp(o).build());
throw new PCEPDeserializerException("Pcmonrep message cannot be empty.");
}
if (!(objects.get(0) instanceof Monitoring)) {
- errors.add(createErrorMsg(PCEPErrors.MONITORING_OBJECT_MISSING, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.MONITORING_OBJECT_MISSING, Optional.absent()));
return null;
}
final PcmonrepMessageBuilder builder = new PcmonrepMessageBuilder();
if (obj instanceof Rp) {
final Rp rp = (Rp) obj;
if (rp.isProcessingRule()) {
- errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.absent()));
return null;
}
requestParameters.add(new RpsBuilder().setRp(rp).build());
protected Replies getValidReply(final List<Object> objects, final List<Message> errors) throws PCEPDeserializerException {
Object object = objects.remove(0);
if (!(object instanceof Rp)) {
- errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.absent()));
return null;
}
final Rp rp = (Rp) object;
if (requests != null) {
mBuilder.setRequests(requests);
} else {
- errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.absent()));
}
if (!objects.isEmpty()) {
throw new PCEPDeserializerException("Unprocessed Objects: " + objects);
Rp rpObj = null;
if (!(objects.get(0) instanceof Rp)) {
// if RP obj is missing return error only
- errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.RP_MISSING, Optional.absent()));
return null;
}
rpObj = (Rp) objects.get(0);
objects.remove(0);
if (!rpObj.isProcessingRule()) {
- errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.absent()));
} else {
rBuilder.setRp(rpObj);
}
}
private enum State {
- START, PROC_TIME, OVERLOAD, END;
+ START, PROC_TIME, OVERLOAD, END
}
}
static {
final MplsLabelCodec mplsLabelCodec = new MplsLabelCodec();
final MplsLabelEntryCodec mplsLabelEntryCodec = new MplsLabelEntryCodec();
- final Builder<Integer, PathBindingTlvCodec> parsers = ImmutableMap.<Integer, PathBindingTlvCodec>builder();
+ final Builder<Integer, PathBindingTlvCodec> parsers = ImmutableMap.builder();
final Builder<Class<? extends BindingTypeValue>, PathBindingTlvCodec> serializers =
- ImmutableMap.<Class<? extends BindingTypeValue>, PathBindingTlvCodec>builder();
+ ImmutableMap.builder();
parsers.put(mplsLabelCodec.getBindingType(), mplsLabelCodec);
serializers.put(MplsLabel.class, mplsLabelCodec);
} else if (obj instanceof Rp) {
final Rp o = (Rp) obj;
if (o.isProcessingRule()) {
- errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.<Rp>absent()));
+ errors.add(createErrorMsg(PCEPErrors.P_FLAG_NOT_SET, Optional.absent()));
return null;
}
requestParameters.add(new RpsBuilder().setRp(o).build());
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.Promise;
}
private void scheduleFailTimer() {
- this.failTimer = this.channel.eventLoop().schedule(new Runnable() {
- @Override
- public void run() {
- switch (AbstractPCEPSessionNegotiator.this.state) {
- case FINISHED:
- case IDLE:
- break;
- case START_TLS_WAIT:
- sendErrorMessage(PCEPErrors.STARTTLS_TIMER_EXP);
- negotiationFailed(new TimeoutException("StartTLSWait timer expired"));
- AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
- break;
- case KEEP_WAIT:
- sendErrorMessage(PCEPErrors.NO_MSG_BEFORE_EXP_KEEPWAIT);
- negotiationFailed(new TimeoutException("KeepWait timer expired"));
- AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
- break;
- case OPEN_WAIT:
- sendErrorMessage(PCEPErrors.NO_OPEN_BEFORE_EXP_OPENWAIT);
- negotiationFailed(new TimeoutException("OpenWait timer expired"));
- AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
- break;
- default:
- break;
- }
+ this.failTimer = this.channel.eventLoop().schedule((Runnable) () -> {
+ switch (AbstractPCEPSessionNegotiator.this.state) {
+ case FINISHED:
+ case IDLE:
+ break;
+ case START_TLS_WAIT:
+ sendErrorMessage(PCEPErrors.STARTTLS_TIMER_EXP);
+ negotiationFailed(new TimeoutException("StartTLSWait timer expired"));
+ AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
+ break;
+ case KEEP_WAIT:
+ sendErrorMessage(PCEPErrors.NO_MSG_BEFORE_EXP_KEEPWAIT);
+ negotiationFailed(new TimeoutException("KeepWait timer expired"));
+ AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
+ break;
+ case OPEN_WAIT:
+ sendErrorMessage(PCEPErrors.NO_OPEN_BEFORE_EXP_OPENWAIT);
+ negotiationFailed(new TimeoutException("OpenWait timer expired"));
+ AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
+ break;
+ default:
+ break;
}
}, FAIL_TIMER_VALUE, TimeUnit.SECONDS);
}
} else {
startNegotiationWithOpen();
}
- this.channel.closeFuture().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture f) {
- cancelTimers();
- }
- });
+ this.channel.closeFuture().addListener((ChannelFutureListener) f -> cancelTimers());
}
private void cancelTimers() {
import com.google.common.base.Preconditions;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
}
protected final void sendMessage(final Message msg) {
- this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture f) {
- if (!f.isSuccess()) {
- LOG.info("Failed to send message {}", msg, f.cause());
- negotiationFailed(f.cause());
- } else {
- LOG.trace("Message {} sent to socket", msg);
- }
-
+ this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
+ if (!f.isSuccess()) {
+ LOG.info("Failed to send message {}", msg, f.cause());
+ negotiationFailed(f.cause());
+ } else {
+ LOG.trace("Message {} sent to socket", msg);
}
+
});
}
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
if (!errors.isEmpty()) {
// We have a bunch of messages, send them out
for (final Object e : errors) {
- ctx.channel().writeAndFlush(e).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture f) {
- if (!f.isSuccess()) {
- LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause());
- } else {
- LOG.trace("Message {} sent to socket {}", e, ctx.channel());
- }
+ ctx.channel().writeAndFlush(e).addListener((ChannelFutureListener) f -> {
+ if (!f.isSuccess()) {
+ LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause());
+ } else {
+ LOG.trace("Message {} sent to socket {}", e, ctx.channel());
}
});
}
@Override
public final void close() {
if (Epoll.isAvailable()) {
- this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);;
- this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);;
+ this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+ this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
}
}
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
}
protected synchronized Short nextSession(final byte[] clientAddress) throws ExecutionException {
- final PeerRecord peer = this.formerClients.get(new ByteArrayWrapper(clientAddress), new Callable<PeerRecord>() {
- @Override
- public PeerRecord call() {
- return new PeerRecord(ID_CACHE_SECONDS, null);
- }
- });
+ final PeerRecord peer = this.formerClients.get(new ByteArrayWrapper(clientAddress), () -> new PeerRecord(ID_CACHE_SECONDS, null));
return peer.allocId();
}
protected synchronized void releaseSession(final byte[] clientAddress, final short sessionId) throws ExecutionException {
- this.formerClients.get(new ByteArrayWrapper(clientAddress), new Callable<PeerRecord>() {
- @Override
- public PeerRecord call() {
- return new PeerRecord(ID_CACHE_SECONDS, sessionId);
- }
- });
+ this.formerClients.get(new ByteArrayWrapper(clientAddress), () -> new PeerRecord(ID_CACHE_SECONDS, sessionId));
}
private static final class ByteArrayWrapper {
}
final EventLoop loop = cf.channel().eventLoop();
- loop.schedule(new Runnable() {
- @Override
- public void run() {
- PCEPProtocolSessionPromise.LOG.debug("Attempting to connect to {}", PCEPProtocolSessionPromise.this.address);
- final Future reconnectFuture = PCEPProtocolSessionPromise.this.b.connect();
- reconnectFuture.addListener(PCEPProtocolSessionPromise.BootstrapConnectListener.this);
- PCEPProtocolSessionPromise.this.pending = reconnectFuture;
- }
+ loop.schedule(() -> {
+ PCEPProtocolSessionPromise.LOG.debug("Attempting to connect to {}", PCEPProtocolSessionPromise.this.address);
+ final Future reconnectFuture = PCEPProtocolSessionPromise.this.b.connect();
+ reconnectFuture.addListener(BootstrapConnectListener.this);
+ PCEPProtocolSessionPromise.this.pending = reconnectFuture;
}, PCEPProtocolSessionPromise.this.retryTimer, TimeUnit.SECONDS);
PCEPProtocolSessionPromise.LOG.debug("Next reconnection attempt in {}s", PCEPProtocolSessionPromise.this.retryTimer);
}
import com.google.common.base.Optional;
import com.google.common.primitives.UnsignedBytes;
import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.Promise;
import java.net.InetSocketAddress;
}
});
- this.channel.closeFuture().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture future) {
- synchronized (lock) {
- sessionReg.removeSessionReference(clientAddress);
- }
+ this.channel.closeFuture().addListener((ChannelFutureListener) future -> {
+ synchronized (lock) {
+ sessionReg.removeSessionReference(clientAddress);
}
});
*/
package org.opendaylight.protocol.pcep.impl.spi;
-import java.util.Arrays;
+import java.util.Collections;
import org.opendaylight.protocol.pcep.spi.PCEPErrors;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.PcerrBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
final ErrorObject err = new ErrorObjectBuilder().setType(e.getErrorType()).setValue(e.getErrorValue()).build();
if (t == null) {
return errMessageBuilder.setPcerrMessage(
- new PcerrMessageBuilder().setErrors(Arrays.asList(new ErrorsBuilder().setErrorObject(err).build())).build()).build();
+ new PcerrMessageBuilder().setErrors(Collections.singletonList(new ErrorsBuilder().setErrorObject(err).build())).build()).build();
} else {
final ErrorType type = new SessionCaseBuilder().setSession(new SessionBuilder().setOpen(t).build()).build();
return errMessageBuilder.setPcerrMessage(
- new PcerrMessageBuilder().setErrors(Arrays.asList(new ErrorsBuilder().setErrorObject(err).build())).setErrorType(type).build()).build();
+ new PcerrMessageBuilder().setErrors(Collections.singletonList(new ErrorsBuilder().setErrorObject(err).build())).setErrorType(type).build()).build();
}
}
}
public class MockPCE implements PCEPSessionListener {
- private final List<Message> listMsg = new ArrayList<Message>();
+ private final List<Message> listMsg = new ArrayList<>();
private PCEPSessionImpl session = null;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.vs.tlv.vs.tlv.VendorPayload;
import org.opendaylight.yangtools.yang.binding.DataContainer;
+@SuppressWarnings("ALL")
public class PCEPTlvParserTest {
private static final byte[] noPathVectorBytes = { 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, (byte) 0xa7 };
import ch.qos.logback.classic.LoggerContext;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.net.InetAddresses;
} else if (args[argIdx].equals("--password")) {
password = args[++argIdx];
} else if (args[argIdx].equals("--reconnect")) {
- reconnectTime = Integer.valueOf(args[++argIdx]).intValue();
+ reconnectTime = Integer.valueOf(args[++argIdx]);
} else if (args[argIdx].equals("--redelegation-timeout")) {
redelegationTimeout = Integer.valueOf(args[++argIdx]);
} else if (args[argIdx].equals("--state-timeout")) {
}
private static ch.qos.logback.classic.Logger getRootLogger(final LoggerContext lc) {
- return Iterables.find(lc.getLoggerList(), new Predicate<Logger>() {
- @Override
- public boolean apply(final Logger input) {
- return (input != null) ? input.getName().equals(Logger.ROOT_LOGGER_NAME) : false;
- }
- });
+ return Iterables.find(lc.getLoggerList(), input -> (input != null) ? input.getName().equals(Logger.ROOT_LOGGER_NAME) : false);
}
}
import com.google.common.net.InetAddresses;
import io.netty.util.Timeout;
import io.netty.util.Timer;
-import io.netty.util.TimerTask;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.Collections;
//check if session really has a delegation
if (hasDelegation(tunnel, session)) {
//send report D=0
- final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.<List<Subobject>>absent());
+ final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.absent());
final Pcrpt pcrtp = createPcRtpMessage(new LspBuilder(update.getLsp()).setSync(true).setOperational(OperationalStatus.Up).setDelegate(false).
setTlvs(tlvs).build(), Optional.of(createSrp(srpId)), tunnel.getLspState());
session.sendReport(pcrtp);
tunnel.cancelTimeouts();
setDelegation(plspId, session);
//send report
- final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.<List<Subobject>>absent());
+ final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.absent());
session.sendReport(createPcRtpMessage(
new LspBuilder(request.getLsp()).setSync(true).setOperational(OperationalStatus.Up).setDelegate(true).setTlvs(tlvs).build(),
Optional.of(createSrp(srpId)), tunnel.getLspState()));
missedLsp <= this.syncOptimization.getLocalLspDbVersionValue().longValue(); missedLsp++) {
final PlspId plspId = new PlspId(missedLsp);
final PCCTunnel tunnel = this.tunnels.get(plspId);
- createLspAndSendReport(missedLsp, tunnel, session, Optional.<Boolean>absent(), NO_SRP);
+ createLspAndSendReport(missedLsp, tunnel, session, Optional.absent(), NO_SRP);
}
}
}
private void sendEndOfSynchronization(final PCCSession session) {
- sendEndOfSynchronization(session, Optional.<SrpIdNumber>absent());
+ sendEndOfSynchronization(session, Optional.absent());
}
private void sendEndOfSynchronization(final PCCSession session, final Optional<SrpIdNumber> operationId) {
tlv = createLspTlvsEndofSync(this.syncOptimization.incrementLspDBVersion().get());
}
final Pcrpt pcrtp = createPcRtpMessage(createLsp(0, false, tlv, true, false), Optional.fromNullable(srp), createPath(Collections
- .<Subobject>emptyList()));
+ .emptyList()));
session.sendReport(pcrtp);
}
private void reportAllKnownLsp(final PCCSession session) {
- reportAllKnownLsp(Optional.<SrpIdNumber>absent(), session);
+ reportAllKnownLsp(Optional.absent(), session);
}
private void reportAllKnownLsp(final Optional<SrpIdNumber> operationId, final PCCSession session) {
for (final Entry<PlspId, PCCTunnel> entry : this.tunnels.entrySet()) {
final PCCTunnel tunnel = entry.getValue();
final long plspId = entry.getKey().getValue();
- createLspAndSendReport(plspId, tunnel, session, Optional.<Boolean>absent(), Optional.fromNullable(srp));
+ createLspAndSendReport(plspId, tunnel, session, Optional.absent(), Optional.fromNullable(srp));
}
}
private void startStateTimeout(final PCCTunnel tunnel, final PlspId plspId) {
if (this.stateTimeout > -1) {
- final Timeout newStateTimeout = this.timer.newTimeout(new TimerTask() {
- @Override
- public void run(final Timeout timeout) throws Exception {
- if (tunnel.getType() == LspType.PCE_LSP) {
- PCCTunnelManagerImpl.this.tunnels.remove(plspId);
- //report tunnel removal to all
- sendToAll(tunnel, plspId, Collections.<Subobject>emptyList(), createSrp(0), new PathBuilder().build(),
- createLsp(plspId.getValue(), false, Optional.<Tlvs>absent(), false, true));
- }
+ final Timeout newStateTimeout = this.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(0), new PathBuilder().build(),
+ createLsp(plspId.getValue(), false, Optional.absent(), false, true));
}
}, this.stateTimeout, TimeUnit.SECONDS);
tunnel.setStateTimeout(newStateTimeout);
}
private void startRedelegationTimer(final PCCTunnel tunnel, final PlspId plspId, final PCCSession session) {
- final Timeout newRedelegationTimeout = this.timer.newTimeout(new TimerTask() {
- @Override
- public void run(final Timeout timeout) throws Exception {
- //remove delegation
- PCCTunnelManagerImpl.this.setDelegation(plspId, null);
- //delegate to another PCE
- int index = session.getId();
- for (int i = 1; i < PCCTunnelManagerImpl.this.sessions.size(); i++) {
- index++;
- if (index == PCCTunnelManagerImpl.this.sessions.size()) {
- index = 0;
- }
- final PCCSession nextSession = PCCTunnelManagerImpl.this.sessions.get(index);
- if (nextSession != null) {
- tunnel.cancelTimeouts();
- final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.<List<Subobject>>absent());
-
- nextSession.sendReport(createPcRtpMessage(
- createLsp(plspId.getValue(), true, Optional.fromNullable(tlvs), true, false), NO_SRP,
- tunnel.getLspState()));
- tunnel.setDelegationHolder(nextSession.getId());
- break;
- }
+ final Timeout newRedelegationTimeout = this.timer.newTimeout(timeout -> {
+ //remove delegation
+ PCCTunnelManagerImpl.this.setDelegation(plspId, null);
+ //delegate to another PCE
+ int index = session.getId();
+ for (int i = 1; i < PCCTunnelManagerImpl.this.sessions.size(); i++) {
+ index++;
+ if (index == PCCTunnelManagerImpl.this.sessions.size()) {
+ index = 0;
+ }
+ final PCCSession nextSession = PCCTunnelManagerImpl.this.sessions.get(index);
+ if (nextSession != null) {
+ tunnel.cancelTimeouts();
+ final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.absent());
+
+ nextSession.sendReport(createPcRtpMessage(
+ createLsp(plspId.getValue(), true, Optional.fromNullable(tlvs), true, false), NO_SRP,
+ tunnel.getLspState()));
+ tunnel.setDelegationHolder(nextSession.getId());
+ break;
}
}
}, this.redelegationTimeout, TimeUnit.SECONDS);
package org.opendaylight.protocol.pcep.pcc.mock.api;
public enum LspType {
- PCE_LSP, PCC_LSP;
+ PCE_LSP, PCC_LSP
}
@Override
public void setPeerSpecificProposal(@Nonnull final InetSocketAddress address, @Nonnull final TlvsBuilder openBuilder) {
Preconditions.checkNotNull(address);
- final LspDbVersion LspDBV = new LspDbVersionBuilder().setLspDbVersionValue(this.dbVersion).build();
- openBuilder.addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(LspDBV).build());
+ final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(this.dbVersion).build();
+ openBuilder.addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(lspDbVersion).build());
}
}
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import org.opendaylight.protocol.pcep.spi.PCEPErrors;
public static Tlvs createLspTlvs(final long lspId, final boolean symbolicPathName, final String tunnelEndpoint,
final String tunnelSender, final String extendedTunnelAddress, final Optional<byte[]> symbolicName) {
- return createLspTlvs(lspId, symbolicPathName, tunnelEndpoint, tunnelSender, extendedTunnelAddress, symbolicName, Optional.<BigInteger>absent());
+ return createLspTlvs(lspId, symbolicPathName, tunnelEndpoint, tunnelSender, extendedTunnelAddress, symbolicName, Optional.absent());
}
public static Tlvs createLspTlvs(final long lspId, final boolean symbolicPathName, final String tunnelEndpoint,
public static Pcerr createErrorMsg(@Nonnull final PCEPErrors e, @Nonnull final long srpId) {
final PcerrMessageBuilder msgBuilder = new PcerrMessageBuilder();
return new PcerrBuilder().setPcerrMessage(
- msgBuilder
- .setErrorType(
- new StatefulCaseBuilder().setStateful(
- new StatefulBuilder().setSrps(
- Lists.newArrayList(new SrpsBuilder().setSrp(
- new SrpBuilder().setProcessingRule(false).setIgnore(false)
- .setOperationId(new SrpIdNumber(srpId)).build())
- .build())).build()).build())
- .setErrors(
- Arrays.asList(new ErrorsBuilder().setErrorObject(
- new ErrorObjectBuilder().setType(e.getErrorType()).setValue(e.getErrorValue())
- .build()).build())).build()).build();
+ msgBuilder
+ .setErrorType(
+ new StatefulCaseBuilder().setStateful(
+ new StatefulBuilder().setSrps(
+ Lists.newArrayList(new SrpsBuilder().setSrp(
+ new SrpBuilder().setProcessingRule(false).setIgnore(false)
+ .setOperationId(new SrpIdNumber(srpId)).build())
+ .build())).build()).build())
+ .setErrors(
+ Collections.singletonList(new ErrorsBuilder().setErrorObject(
+ new ErrorObjectBuilder().setType(e.getErrorType()).setValue(e.getErrorValue())
+ .build()).build())).build()).build();
}
public static byte[] getDefaultPathName(final String address, final long lspId) {
for (final Reports report : pcrt) {
final Lsp lsp = report.getLsp();
if (lsp.getPlspId().getValue() == 0) {
- assertEquals(false, lsp.isSync().booleanValue());
+ assertEquals(false, lsp.isSync());
} else {
- assertEquals(true, lsp.isSync().booleanValue());
+ assertEquals(true, lsp.isSync());
}
final BigInteger actuaLspDBVersion = lsp.getTlvs().getAugmentation(org.opendaylight.yang.gen
.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class)
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.pcep.pcc.mock.api.PCCSession;
import org.opendaylight.protocol.pcep.pcc.mock.api.PCCTunnelManager;
import org.opendaylight.protocol.pcep.spi.PCEPErrors;
public void setUp() {
MockitoAnnotations.initMocks(this);
Mockito.doNothing().when(this.session1).sendReport(Mockito.any(Pcrpt.class));
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- PCCTunnelManagerImplTest.this.errorsSession1.add(getError((Pcerr) invocation.getArguments()[0]));
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ PCCTunnelManagerImplTest.this.errorsSession1.add(getError((Pcerr) invocation.getArguments()[0]));
+ return null;
}).when(this.session1).sendError(Mockito.any(Pcerr.class));
Mockito.doReturn(0).when(this.session1).getId();
Mockito.doNothing().when(this.session2).sendReport(Mockito.any(Pcrpt.class));
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- PCCTunnelManagerImplTest.this.errorsSession2.add(getError((Pcerr) invocation.getArguments()[0]));
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ PCCTunnelManagerImplTest.this.errorsSession2.add(getError((Pcerr) invocation.getArguments()[0]));
+ return null;
}).when(this.session2).sendError(Mockito.any(Pcerr.class));
Mockito.doReturn(1).when(this.session2).getId();
}
import com.google.common.primitives.UnsignedBytes;
import io.netty.buffer.ByteBuf;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
rp.get()).build())).build()).build();
}
return new PcerrBuilder().setPcerrMessage(
- msgBuilder.setErrors(Arrays.asList(new ErrorsBuilder().setErrorObject(
- new ErrorObjectBuilder().setType(e.getErrorType()).setValue(
- e.getErrorValue()).build()).build())).build()).build();
+ msgBuilder.setErrors(Collections.singletonList(new ErrorsBuilder().setErrorObject(
+ new ErrorObjectBuilder().setType(e.getErrorType()).setValue(
+ e.getErrorValue()).build()).build())).build()).build();
}
protected abstract Message validate(final List<Object> objects, final List<Message> errors) throws PCEPDeserializerException;
* @return true if setup is via RSVP-TE signaling protocol
*/
public static boolean isDefaultPST(final PathSetupType pst) {
- if (pst != null && pst.getPst() != null && pst.getPst().shortValue() != 0) {
+ if (pst != null && pst.getPst() != null && pst.getPst() != 0) {
return false;
}
return true;
package org.opendaylight.protocol.pcep.spi;
import com.google.common.base.Preconditions;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcep.error.object.ErrorObjectBuilder;
}
public List<Errors> getErrors() {
- return Arrays.asList(this.error);
+ return Collections.singletonList(this.error);
}
public PCEPErrors getError() {
Mockito.verify(this.registry, Mockito.only()).serializeObject(Mockito.any(Object.class), Mockito.any(ByteBuf.class));
- final Message b = a.parseMessage(Unpooled.wrappedBuffer(new byte[] {0x0D, 0x13, 0, 0x08, 0, 0, 1, 1 }), Collections.<Message> emptyList());
+ final Message b = a.parseMessage(Unpooled.wrappedBuffer(new byte[] {0x0D, 0x13, 0, 0x08, 0, 0, 1, 1 }), Collections.emptyList());
assertEquals(this.object, ((Pcerr) b).getPcerrMessage().getErrors().get(0).getErrorObject());
}
parser.serializeVendorInformationObjects(Lists.newArrayList(this.viObject), buffer);
Mockito.verify(this.registry, Mockito.only()).serializeVendorInformationObject(Mockito.any(VendorInformationObject.class), Mockito.any(ByteBuf.class));
- final Message msg = parser.parseMessage(Unpooled.wrappedBuffer(new byte[] {0x22, 0x13, 0x00, 0x08, 0, 0, 0, 0 }), Collections.<Message> emptyList());
+ final Message msg = parser.parseMessage(Unpooled.wrappedBuffer(new byte[] {0x22, 0x13, 0x00, 0x08, 0, 0, 0, 0 }), Collections.emptyList());
assertEquals(this.viObject, ((Pcrep)msg).getPcrepMessage().getReplies().get(0).getVendorInformationObject().get(0));
}
protected void addVendorInformationTlvs(TlvsBuilder builder, List<VendorInformationTlv> tlvs) {
builder.setVendorInformationTlv(tlvs);
}
- };
+ }
@Before
public void setUp() throws PCEPDeserializerException {
this.ctx.getObjectHandlerRegistry().parseObject(4, 1, new ObjectHeaderImpl(true, false), buffer);
this.ctx.getObjectHandlerRegistry().serializeObject(new OpenBuilder().build(), buffer);
- this.ctx.getMessageHandlerRegistry().parseMessage(6, buffer, Collections.<Message> emptyList());
+ this.ctx.getMessageHandlerRegistry().parseMessage(6, buffer, Collections.emptyList());
this.ctx.getMessageHandlerRegistry().serializeMessage(new KeepaliveBuilder().build(), buffer);
this.ctx.getVendorInformationObjectRegistry().parseVendorInformationObject(new EnterpriseNumber(10L), new ObjectHeaderImpl(true, false), buffer);
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.opendaylight.protocol.pcep.PCEPCapability;
-import org.opendaylight.protocol.pcep.PCEPSessionListener;
-import org.opendaylight.protocol.pcep.PCEPSessionListenerFactory;
import org.opendaylight.protocol.pcep.PCEPSessionNegotiatorFactory;
import org.opendaylight.protocol.pcep.PCEPSessionProposalFactory;
import org.opendaylight.protocol.pcep.impl.BasePCEPSessionProposalFactory;
final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(0);
try (final PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry())) {
- pccDispatcher.createClient(serverAddr, -1, new PCEPSessionListenerFactory() {
- @Override
- public PCEPSessionListener getSessionListener() {
- return new SimpleSessionListener();
- }
- }, snf, null, clientAddr).get();
+ pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf, null, clientAddr).get();
}
}
}
this.listenerState.updateStatefulSentMsg(message);
final PCEPRequest req = new PCEPRequest(metadata);
this.requests.put(requestId, req);
- final short rpcTimeout = serverSessionManager.getRpcTimeout();
+ final short rpcTimeout = this.serverSessionManager.getRpcTimeout();
LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
if (rpcTimeout > 0) {
setupTimeoutHandler(requestId, req, rpcTimeout);
static final OperationResults SUCCESS = new OperationResults((FailureType)null);
static final OperationResults UNSENT = new OperationResults(FailureType.Unsent);
- private static final Function<Errors, Error> CONVERT_ERRORS = new Function<Errors, Error>() {
- @Override
- public Error apply(final Errors input) {
- return new ErrorBuilder(input).build();
- }
- };
+ private static final Function<Errors, Error> CONVERT_ERRORS = input -> new ErrorBuilder(input).build();
private final FailureType failure;
private final List<Error> error;
}
ListenableFuture<OperationResult> future() {
- return Futures.<OperationResult> immediateFuture(this);
+ return Futures.immediateFuture(this);
}
public static OperationResults createFailed(final List<Errors> errors) {
- final List<Errors> e = errors != null ? errors : Collections.<Errors>emptyList();
+ final List<Errors> e = errors != null ? errors : Collections.emptyList();
return new OperationResults(FailureType.Failed, Lists.transform(e, CONVERT_ERRORS));
}
public static OperationResults createUnsent(final PCEPErrors error) {
- final List<Errors> e = error != null ? Collections.singletonList(getErrorFor(error)) : Collections.<Errors>emptyList();
+ final List<Errors> e = error != null ? Collections.singletonList(getErrorFor(error)) : Collections.emptyList();
return new OperationResults(FailureType.Unsent, Lists.transform(e, CONVERT_ERRORS));
}
final Stateful stateful = tlvs.getAugmentation(Tlvs1.class).getStateful();
if (stateful != null) {
getSessionListenerState().setPeerCapabilities(getCapabilities(stateful));
- pccBuilder.setReportedLsp(Collections.<ReportedLsp> emptyList());
+ pccBuilder.setReportedLsp(Collections.emptyList());
if (isSynchronized()) {
pccBuilder.setStateSync(PccSyncState.Synchronized);
} else if (isTriggeredInitialSynchro()) {
if (f == null) {
return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
}
- return Futures.transform(f, new AsyncFunction<Optional<ReportedLsp>, OperationResult>() {
- @Override
- public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
- final Lsp reportedLsp = validateReportedLsp(rep, input);
- if (reportedLsp == null) {
- return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
- }
- final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
- final Requests rb = buildRequest(rep, reportedLsp);
- ib.setRequests(Collections.singletonList(rb));
- return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null);
+ return Futures.transform(f, (AsyncFunction<Optional<ReportedLsp>, OperationResult>) rep -> {
+ final Lsp reportedLsp = validateReportedLsp(rep, input);
+ if (reportedLsp == null) {
+ return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
}
+ final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
+ final Requests rb = buildRequest(rep, reportedLsp);
+ ib.setRequests(Collections.singletonList(rb));
+ return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null);
});
}
}
private ListenableFuture<OperationResult> listenableFuture(final ListenableFuture<Optional<ReportedLsp>> f, final EnsureLspOperationalInput input, final OperationalStatus op) {
- return Futures.transform(f, new Function<Optional<ReportedLsp>, OperationResult>() {
- @Override
- public OperationResult apply(final Optional<ReportedLsp> rep) {
- if (!rep.isPresent()) {
- LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
+ return Futures.transform(f, (Function<Optional<ReportedLsp>, OperationResult>) rep -> {
+ if (!rep.isPresent()) {
+ 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().getPath()) {
+ final Path1 p1 = p.getAugmentation(Path1.class);
+ if (p1 == null) {
+ LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
return OperationResults.UNSENT;
}
- // check if at least one of the paths has the same status as requested
- for (final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path p : rep.get().getPath()) {
- final Path1 p1 = p.getAugmentation(Path1.class);
- if (p1 == null) {
- LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
- return OperationResults.UNSENT;
- }
- if (op.equals(p1.getLsp().getOperational())) {
- return OperationResults.SUCCESS;
- }
+ if (op.equals(p1.getLsp().getOperational())) {
+ return OperationResults.SUCCESS;
}
- return OperationResults.UNSENT;
}
+ return OperationResults.UNSENT;
});
}
@Override
public Future<RpcResult<AddLspOutput>> addLsp(final AddLspInput input) {
- return Futures.transform(manager.addLsp(input), new Function<OperationResult, RpcResult<AddLspOutput>>() {
- @Override
- public RpcResult<AddLspOutput> apply(final OperationResult input) {
- return SuccessfulRpcResult.create(new AddLspOutputBuilder(input).build());
- }
- });
+ return Futures.transform(manager.addLsp(input), (Function<OperationResult, RpcResult<AddLspOutput>>) input1 -> SuccessfulRpcResult.create(new AddLspOutputBuilder(input1).build()));
}
@Override
public Future<RpcResult<RemoveLspOutput>> removeLsp(final RemoveLspInput input) {
- return Futures.transform(manager.removeLsp(input), new Function<OperationResult, RpcResult<RemoveLspOutput>>() {
- @Override
- public RpcResult<RemoveLspOutput> apply(final OperationResult input) {
- return SuccessfulRpcResult.create(new RemoveLspOutputBuilder(input).build());
- }
- });
+ return Futures.transform(manager.removeLsp(input), (Function<OperationResult, RpcResult<RemoveLspOutput>>) input1 -> SuccessfulRpcResult.create(new RemoveLspOutputBuilder(input1).build()));
}
@Override
public Future<RpcResult<TriggerSyncOutput>> triggerSync(final TriggerSyncInput input) {
- return Futures.transform(manager.triggerSync(input), new Function<OperationResult, RpcResult<TriggerSyncOutput>>() {
- @Override
- public RpcResult<TriggerSyncOutput> apply(final OperationResult input) {
- return SuccessfulRpcResult.create(new TriggerSyncOutputBuilder(input).build());
- }
- });
+ return Futures.transform(manager.triggerSync(input), (Function<OperationResult, RpcResult<TriggerSyncOutput>>) input1 -> SuccessfulRpcResult.create(new TriggerSyncOutputBuilder(input1).build()));
}
@Override
public Future<RpcResult<UpdateLspOutput>> updateLsp(final UpdateLspInput input) {
- return Futures.transform(manager.updateLsp(input), new Function<OperationResult, RpcResult<UpdateLspOutput>>() {
- @Override
- public RpcResult<UpdateLspOutput> apply(final OperationResult input) {
- return SuccessfulRpcResult.create(new UpdateLspOutputBuilder(input).build());
- }
- });
+ return Futures.transform(manager.updateLsp(input), (Function<OperationResult, RpcResult<UpdateLspOutput>>) input1 -> SuccessfulRpcResult.create(new UpdateLspOutputBuilder(input1).build()));
}
@Override
public Future<RpcResult<EnsureLspOperationalOutput>> ensureLspOperational(final EnsureLspOperationalInput input) {
return Futures.transform(manager.ensureLspOperational(input),
- new Function<OperationResult, RpcResult<EnsureLspOperationalOutput>>() {
- @Override
- public RpcResult<EnsureLspOperationalOutput> apply(final OperationResult input) {
- return SuccessfulRpcResult.create(new EnsureLspOperationalOutputBuilder(input).build());
- }
- });
+ (Function<OperationResult, RpcResult<EnsureLspOperationalOutput>>) input1 -> SuccessfulRpcResult.create(new EnsureLspOperationalOutputBuilder(input1).build()));
}
}
return Futures.transform(
(ListenableFuture<RpcResult<AddLspOutput>>) this.topologyService.addLsp(addLspInput),
- new Function<RpcResult<AddLspOutput>, OperationResult>() {
- @Override
- public OperationResult apply(final RpcResult<AddLspOutput> input) {
- return input.getResult();
- }
- });
+ (Function<RpcResult<AddLspOutput>, OperationResult>) RpcResult::getResult);
}
}
if (sc.getIpv4Address() != null) {
for (final IpAddress dc : dsts) {
if (dc.getIpv4Address() != null) {
- return Optional.<AddressFamily>of(new Ipv4CaseBuilder().setIpv4(new Ipv4Builder().setSourceIpv4Address(sc.getIpv4Address()).
+ return Optional.of(new Ipv4CaseBuilder().setIpv4(new Ipv4Builder().setSourceIpv4Address(sc.getIpv4Address()).
setDestinationIpv4Address(dc.getIpv4Address()).build()).build());
}
}
if (sc.getIpv6Address() != null) {
for (final IpAddress dc : dsts) {
if (dc.getIpv6Address() != null) {
- return Optional.<AddressFamily>of(new Ipv6CaseBuilder().setIpv6(new Ipv6Builder().setSourceIpv6Address(sc.getIpv6Address()).
+ return Optional.of(new Ipv6CaseBuilder().setIpv6(new Ipv6Builder().setSourceIpv6Address(sc.getIpv6Address()).
setDestinationIpv6Address(dc.getIpv6Address()).build()).build());
}
}
ab.setNode(node.getSupportingNode().get(0).getKey().getNodeRef());
return Futures.transform(
(ListenableFuture<RpcResult<RemoveLspOutput>>) this.topologyService.removeLsp(ab.build()),
- new Function<RpcResult<RemoveLspOutput>, OperationResult>() {
- @Override
- public OperationResult apply(final RpcResult<RemoveLspOutput> input) {
- return input.getResult();
- }
- });
+ (Function<RpcResult<RemoveLspOutput>, OperationResult>) RpcResult::getResult);
}
}
}
import org.slf4j.LoggerFactory;
final class TunelProgrammingUtil {
- public static final ListenableFuture<OperationResult> RESULT = Futures.<OperationResult>immediateFuture(new OperationResult() {
+ public static final ListenableFuture<OperationResult> RESULT = Futures.immediateFuture(new OperationResult() {
@Override
public Class<? extends DataContainer> getImplementedInterface() {
return OperationResult.class;
}
return Futures.transform(
(ListenableFuture<RpcResult<UpdateLspOutput>>) this.topologyService.updateLsp(buildUpdateInput(link, node)),
- new Function<RpcResult<UpdateLspOutput>, OperationResult>() {
- @Override
- public OperationResult apply(final RpcResult<UpdateLspOutput> input) {
- return input.getResult();
- }
- });
+ (Function<RpcResult<UpdateLspOutput>, OperationResult>) RpcResult::getResult);
}
}
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
-import java.util.concurrent.Future;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.bgpcep.programming.spi.Instruction;
import org.opendaylight.bgpcep.programming.spi.InstructionScheduler;
import org.opendaylight.bgpcep.programming.spi.SchedulerException;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
+@SuppressWarnings("ALL")
public class TunnelProgrammingTest extends AbstractDataBrokerTest {
private static final TopologyId TOPOLOGY_ID = new TopologyId("tunnel-topo");
MockitoAnnotations.initMocks(this);
Mockito.doReturn(true).when(this.instruction).checkedExecutionStart();
Mockito.doNothing().when(this.instruction).executionCompleted(InstructionStatus.Failed, null);
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(this.instructionFuture).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(this.futureAddLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(this.futureUpdateLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
- Mockito.doAnswer(new Answer<Void>() {
- @Override
- public Void answer(final InvocationOnMock invocation) throws Throwable {
- final Runnable callback = (Runnable) invocation.getArguments()[0];
- callback.run();
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Runnable callback = (Runnable) invocation.getArguments()[0];
+ callback.run();
+ return null;
}).when(this.futureRemoveLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
- Mockito.doAnswer(new Answer<Future<RpcResult<AddLspOutput>>>() {
- @Override
- public Future<RpcResult<AddLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
- TunnelProgrammingTest.this.addLspInput = (AddLspInput) invocation.getArguments()[0];
- return TunnelProgrammingTest.this.futureAddLspOutput;
- }
+ Mockito.doAnswer(invocation -> {
+ TunnelProgrammingTest.this.addLspInput = (AddLspInput) invocation.getArguments()[0];
+ return TunnelProgrammingTest.this.futureAddLspOutput;
}).when(this.topologyService).addLsp(Mockito.any(AddLspInput.class));
- Mockito.doAnswer(new Answer<Future<RpcResult<UpdateLspOutput>>>() {
- @Override
- public Future<RpcResult<UpdateLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
- TunnelProgrammingTest.this.updateLspInput = (UpdateLspInput) invocation.getArguments()[0];
- return TunnelProgrammingTest.this.futureUpdateLspOutput;
- }
+ Mockito.doAnswer(invocation -> {
+ TunnelProgrammingTest.this.updateLspInput = (UpdateLspInput) invocation.getArguments()[0];
+ return TunnelProgrammingTest.this.futureUpdateLspOutput;
}).when(this.topologyService).updateLsp(Mockito.any(UpdateLspInput.class));
- Mockito.doAnswer(new Answer<Future<RpcResult<RemoveLspOutput>>>() {
- @Override
- public Future<RpcResult<RemoveLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
- TunnelProgrammingTest.this.removeLspInput = (RemoveLspInput) invocation.getArguments()[0];
- return TunnelProgrammingTest.this.futureRemoveLspOutput;
- }
+ Mockito.doAnswer(invocation -> {
+ TunnelProgrammingTest.this.removeLspInput = (RemoveLspInput) invocation.getArguments()[0];
+ return TunnelProgrammingTest.this.futureRemoveLspOutput;
}).when(this.topologyService).removeLsp(Mockito.any(RemoveLspInput.class));
- Mockito.doReturn(instruction).when(this.instructionFuture).get();
+ Mockito.doReturn(this.instruction).when(this.instructionFuture).get();
Mockito.doReturn(this.instructionFuture).when(this.scheduler).scheduleInstruction(Mockito.any(SubmitInstructionInput.class));
createInitialTopology();
- this.tunnelProgramming = new TunnelProgramming(scheduler, getDataBroker(), topologyService);
+ this.tunnelProgramming = new TunnelProgramming(this.scheduler, getDataBroker(), this.topologyService);
}
@Test
createInputBuilder.setBandwidth(bwd);
createInputBuilder.setClassType(classType);
createInputBuilder.setSymbolicPathName(tunnelName);
- createInputBuilder.setExplicitHops(Lists.<ExplicitHops>newArrayList());
+ createInputBuilder.setExplicitHops(Lists.newArrayList());
createInputBuilder.addAugmentation(PcepCreateP2pTunnelInput1.class, new PcepCreateP2pTunnelInput1Builder().setAdministrativeStatus(AdministrativeStatus.Active).build());
this.tunnelProgramming.pcepCreateP2pTunnel(createInputBuilder.build());
//check add-lsp input
public SimpleRSVPExtensionProviderContext(final int maximumCachedObjects) {
final Cache<Object, Object> cache = CacheBuilder.newBuilder().maximumSize(maximumCachedObjects).build();
- this.cacheRef = new AtomicReference<Cache<Object,Object>>(cache);
+ this.cacheRef = new AtomicReference<>(cache);
}
@Override
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.EROSubobjectParser;
import org.opendaylight.protocol.rsvp.parser.spi.EROSubobjectSerializer;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
Mockito.doReturn(new SubobjectContainerBuilder().build()).when(this.rroSubobjectParser).parseSubobject(this.input, false);
final ArgumentCaptor<SubobjectContainer> arg = ArgumentCaptor.forClass(SubobjectContainer.class);
final ArgumentCaptor<ByteBuf> bufArg = ArgumentCaptor.forClass(ByteBuf.class);
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
+ return null;
}).when(this.rroSubobjectSerializer).serializeSubobject(arg.capture(), bufArg.capture());
}
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.RROSubobjectParser;
import org.opendaylight.protocol.rsvp.parser.spi.RROSubobjectSerializer;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
Mockito.doReturn(new SubobjectContainerBuilder().build()).when(this.rroSubobjectParser).parseSubobject(this.input);
final ArgumentCaptor<SubobjectContainer> arg = ArgumentCaptor.forClass(SubobjectContainer.class);
final ArgumentCaptor<ByteBuf> bufArg = ArgumentCaptor.forClass(ByteBuf.class);
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
+ return null;
}).when(this.rroSubobjectSerializer).serializeSubobject(arg.capture(), bufArg.capture());
}
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
import org.opendaylight.protocol.rsvp.parser.spi.XROSubobjectParser;
import org.opendaylight.protocol.rsvp.parser.spi.XROSubobjectSerializer;
.input, false);
final ArgumentCaptor<SubobjectContainer> arg = ArgumentCaptor.forClass(SubobjectContainer.class);
final ArgumentCaptor<ByteBuf> bufArg = ArgumentCaptor.forClass(ByteBuf.class);
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ ((ByteBuf) args[1]).writeBoolean(Boolean.TRUE);
+ return null;
}).when(this.rroSubobjectSerializer).serializeSubobject(arg.capture(), bufArg.capture());
}
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.EROSubobjectRegistry;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.AttributeFilter;
@Before
public void setUp() throws RSVPParsingException {
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
- return null;
- }
- return EROSubobjectListParserTest.this.subObj;
+ Mockito.doAnswer(invocation -> {
+ if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
+ return null;
}
+ return EROSubobjectListParserTest.this.subObj;
}).when(this.registry).parseSubobject(Mockito.anyInt(), Mockito.any(ByteBuf.class), Mockito.anyBoolean());
Mockito.doReturn("lala").when(this.subObj).toString();
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
+ return null;
}).when(this.registry).serializeSubobject(Mockito.any(SubobjectContainer.class), Mockito.any(ByteBuf.class));
}
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.RROSubobjectRegistry;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.RsvpTeObject;
@Before
public void setUp() throws RSVPParsingException {
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
- return null;
- }
- return RROSubobjectListParserTest.this.subObj;
+ Mockito.doAnswer(invocation -> {
+ if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
+ return null;
}
+ return RROSubobjectListParserTest.this.subObj;
}).when(this.registry).parseSubobject(Mockito.anyInt(), Mockito.any(ByteBuf.class));
Mockito.doReturn("lala").when(this.subObj).toString();
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
+ return null;
}).when(this.registry).serializeSubobject(Mockito.any(SubobjectContainer.class), Mockito.any(ByteBuf.class));
}
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
import org.opendaylight.protocol.rsvp.parser.spi.XROSubobjectRegistry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.RsvpTeObject;
@Before
public void setUp() throws RSVPParsingException {
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
- return null;
- }
- return XROSubobjectListParserTest.this.subObj;
+ Mockito.doAnswer(invocation -> {
+ if (((ByteBuf) invocation.getArguments()[1]).readableBytes() == 0) {
+ return null;
}
+ return XROSubobjectListParserTest.this.subObj;
}).when(this.registry).parseSubobject(Mockito.anyInt(), Mockito.any(ByteBuf.class), Mockito.anyBoolean());
Mockito.doReturn("lala").when(this.subObj).toString();
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ ((ByteBuf) invocation.getArguments()[1]).writeByte(1);
+ return null;
}).when(this.registry).serializeSubobject(Mockito.any(SubobjectContainer.class), Mockito.any(ByteBuf.class));
}