@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);
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());
final SchemaContext context = parseYangStreams(getFilesAsStreams(getYangModelsPaths()));
final SchemaService mockedSchemaService = mock(SchemaService.class);
doReturn(context).when(mockedSchemaService).getGlobalContext();
- doAnswer(new Answer<ListenerRegistration<SchemaContextListener>>() {
- @Override
- public ListenerRegistration<SchemaContextListener> answer(final InvocationOnMock invocation) {
- invocation.getArgumentAt(0, SchemaContextListener.class).onGlobalContextUpdated(context);
- final 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);
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
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) {
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;
}
@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();
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());
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
public BGPFileWatcher() throws IOException {
this.watchService = FileSystems.getDefault().newWatchService();
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- try {
- BGPFileWatcher.this.watchService.close();
- } catch (final IOException e) {
- LOG.warn(INTERRUPTED, e);
- }
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ try {
+ BGPFileWatcher.this.watchService.close();
+ } catch (final IOException e) {
+ LOG.warn(INTERRUPTED, e);
}
- });
+ }));
PATH.register(this.watchService, OVERFLOW, ENTRY_CREATE);
}
@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(" ", " ");
}
@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
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());
}
doReturn(false).when(this.sessionState).isAsn32CapabilitySupported();
doReturn(false).when(this.sessionState).isAddPathCapabilitySupported();
doReturn(this.state).when(this.sessionState).getSessionState();
- Mockito.doAnswer(new Answer<State>() {
- @Override
- public State answer(final InvocationOnMock invocation) throws Throwable {
- return NeighborUtilTest.this.state;
- }
- }).when(this.sessionState).getSessionState();
+ Mockito.doAnswer(invocation -> NeighborUtilTest.this.state).when(this.sessionState).getSessionState();
doReturn(Collections.singleton(TABLES_KEY)).when(this.bgpAfiSafiState).getAfiSafisAdvertized();
doReturn(Collections.singleton(TABLES_KEY)).when(this.bgpAfiSafiState).getAfiSafisReceived();
- Mockito.doAnswer(new Answer<Optional>() {
- @Override
- public Optional answer(final InvocationOnMock invocation) throws Throwable {
- return NeighborUtilTest.this.afiSafi;
- }
- }).when(this.tableRegistry).getAfiSafiType(eq(TABLES_KEY));
+ Mockito.doAnswer(invocation -> NeighborUtilTest.this.afiSafi).when(this.tableRegistry).getAfiSafiType(eq(TABLES_KEY));
doReturn(false).when(this.bgpAfiSafiState).isAfiSafiSupported(eq(TABLES_KEY));
doReturn(false).when(this.bgpAfiSafiState).isGracefulRestartAdvertized(eq(TABLES_KEY));
doReturn(false).when(this.bgpAfiSafiState).isGracefulRestartReceived(eq(TABLES_KEY));
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
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);
}
private void mockTransactionChain() {
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- yIIChanges.add((YangInstanceIdentifier) args[1]);
- return args[1];
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ yIIChanges.add((YangInstanceIdentifier) args[1]);
+ 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();
- if (routePaYii.equals(args[1])) {
- yIIChanges.remove(routePaYii);
- } else if (routePaAddPathYii.equals(args[1])) {
- yIIChanges.remove(routePaAddPathYii);
- } else if (routeRiboutYii.equals(args[1])) {
- yIIChanges.remove(routeRiboutYii);
- yIIChanges.remove(routeAddRiboutAttYii);
- } else if (routeAddRiboutYii.equals(args[1])) {
- yIIChanges.remove(routeAddRiboutYii);
- yIIChanges.remove(routeAddRiboutAttYii);
- }
- return args[1];
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ if (routePaYii.equals(args[1])) {
+ yIIChanges.remove(routePaYii);
+ } else if (routePaAddPathYii.equals(args[1])) {
+ yIIChanges.remove(routePaAddPathYii);
+ } else if (routeRiboutYii.equals(args[1])) {
+ yIIChanges.remove(routeRiboutYii);
+ yIIChanges.remove(routeAddRiboutAttYii);
+ } else if (routeAddRiboutYii.equals(args[1])) {
+ yIIChanges.remove(routeAddRiboutYii);
+ yIIChanges.remove(routeAddRiboutAttYii);
}
+ return args[1];
}).when(this.tx).delete(Mockito.any(LogicalDatastoreType.class), Mockito.any(YangInstanceIdentifier.class));
}
private void mockExportPolicies() {
Mockito.doReturn(true).when(this.peerPT).isTableSupported(PEER_ID);
Mockito.doReturn(false).when(this.peerPT).isTableSupported(PEER_ID2);
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- if (PeerRole.Ibgp.equals(args[0])) {
- return peg;
- } else if (PeerRole.Ebgp.equals(args[0])) {
- return pegNot;
- } else {
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ if (PeerRole.Ibgp.equals(args[0])) {
+ return peg;
+ } else if (PeerRole.Ebgp.equals(args[0])) {
+ return pegNot;
+ } else {
+ return null;
}
}).when(this.peerPT).getPeerGroup(Mockito.any(PeerRole.class));
Mockito.doReturn(ROUTE_ATTRIBUTES_IDENTIFIER).when(this.ribSupport).routeAttributesIdentifier();
Mockito.doReturn(ROUTE_ID_PA_ADD_PATH).when(this.ribSupport).getRouteIdAddPath(Mockito.any(Long.class), Mockito.eq(ROUTE_ID_PA_ADD_PATH));
Mockito.doReturn(null).when(this.ribSupport).getRouteIdAddPath(Mockito.any(Long.class), Mockito.eq(ROUTE_ID_PA));
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
- final YangInstanceIdentifier yii = (YangInstanceIdentifier) args[0];
- final PathArgument paa = (PathArgument) args[1];
-
- if (ROUTE_ID_PA.equals(paa)) {
- if (yii.equals(locRibTargetYii)) {
- return routePaYii;
- } else if (yii.equals(locRibOutTargetYii)) {
- return routeRiboutYii;
- } else if (yii.equals(locRibOutTargetYiiPeer2)) {
- return routeRiboutYiiPeer2;
- }
- } else if (ROUTE_ID_PA_ADD_PATH.equals(paa)) {
- if (yii.equals(locRibTargetYii)) {
- return routePaAddPathYii;
- } else if (yii.equals(locRibOutTargetYii)) {
- return routeAddRiboutYii;
- } else if (yii.equals(locRibOutTargetYiiPeer2)) {
- return routeAddRiboutYiiPeer2;
- }
+ Mockito.doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ final YangInstanceIdentifier yii = (YangInstanceIdentifier) args[0];
+ final PathArgument paa = (PathArgument) args[1];
+
+ if (ROUTE_ID_PA.equals(paa)) {
+ if (yii.equals(locRibTargetYii)) {
+ return routePaYii;
+ } else if (yii.equals(locRibOutTargetYii)) {
+ return routeRiboutYii;
+ } else if (yii.equals(locRibOutTargetYiiPeer2)) {
+ return routeRiboutYiiPeer2;
+ }
+ } else if (ROUTE_ID_PA_ADD_PATH.equals(paa)) {
+ if (yii.equals(locRibTargetYii)) {
+ return routePaAddPathYii;
+ } else if (yii.equals(locRibOutTargetYii)) {
+ return routeAddRiboutYii;
+ } else if (yii.equals(locRibOutTargetYiiPeer2)) {
+ return routeAddRiboutYiiPeer2;
}
- return null;
}
+ return null;
}).when(this.ribSupport).routePath(Mockito.any(YangInstanceIdentifier.class), Mockito.any(PathArgument.class));
}
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 {
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 ChannelFuture f = mock(ChannelFuture.class);
doReturn(null).when(f).addListener(Mockito.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();
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));
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();
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();
@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(mock(GeneratedClassLoadingStrategy.class)).when(this.extension).getClassLoadingStrategy();
@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(AbstractRIBSupportTest.this.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(AbstractRIBSupportTest.this.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()));
@Override
public final void setUp() throws Exception {
super.setUp();
- setupMockService(TopologyReference.class, new TopologyReference() {
- @Override
- public InstanceIdentifier<Topology> getInstanceIdentifier() {
- return null;
- }
- });
+ setupMockService(TopologyReference.class, (TopologyReference) () -> null);
setupMockService(BgpTopologyDeployer.class, new BgpTopologyDeployer() {
@Override
public AbstractRegistration registerTopologyProvider(final BgpTopologyProvider topologyBuilder) {
}
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() {
}
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);
}
+
});
}
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());
}
});
}
}
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);
}
}
});
- 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);
}
});
public final void setUp() {
MockitoAnnotations.initMocks(this);
final ChannelFuture future = new DefaultChannelPromise(this.channel);
- doAnswer(new Answer<Object>() {
- @Override
- public Object answer(final InvocationOnMock invocation) {
- final Object[] args = invocation.getArguments();
- AbstractPCEPSessionTest.this.msgsSend.add((Notification) args[0]);
- return future;
- }
+ doAnswer(invocation -> {
+ final Object[] args = invocation.getArguments();
+ AbstractPCEPSessionTest.this.msgsSend.add((Notification) args[0]);
+ return future;
}).when(this.channel).writeAndFlush(any(Notification.class));
doReturn(this.channelFuture).when(this.channel).closeFuture();
doReturn(this.channelFuture).when(this.channelFuture).addListener(any(GenericFutureListener.class));
}
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);
}
}
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.emptyList(), createSrp(0), new PathBuilder().build(),
- createLsp(plspId.getValue(), false, Optional.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.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);
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();
}
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();
}
}
}
setupTimeoutHandler(requestId, req, rpcTimeout);
}
- f.addListener(new FutureListener<Void>() {
- @Override
- public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
- if (!future.isSuccess()) {
- synchronized (AbstractTopologySessionListener.this) {
- AbstractTopologySessionListener.this.requests.remove(requestId);
- }
- req.done(OperationResults.UNSENT);
- LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
- } else {
- req.sent();
- LOG.trace("Request {} sent to peer (object {})", requestId, req);
+ f.addListener((FutureListener<Void>) future -> {
+ if (!future.isSuccess()) {
+ synchronized (AbstractTopologySessionListener.this) {
+ AbstractTopologySessionListener.this.requests.remove(requestId);
}
+ req.done(OperationResults.UNSENT);
+ LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
+ } else {
+ req.sent();
+ LOG.trace("Request {} sent to peer (object {})", requestId, req);
}
});
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;
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);
}
}
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);
}
}
}
}
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);
}
}
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());
}
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());
}
.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());
}
@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));
}
@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));
}
@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));
}