Bump MRI upstreams
[lispflowmapping.git] / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.java
1 /*
2  * Copyright (c) 2014, 2017 Contextream, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.lispflowmapping.integrationtest;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A;
16 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A_SB;
17 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B;
18 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B_SB;
19 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C;
20 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_NEGATIVE;
21 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_RLOC_10;
22 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_SB;
23 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_100_1_SB;
24 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_50_2_SB;
25 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D4;
26 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D5;
27 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_DELETE_SB;
28 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_100_1_SB;
29 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_50_2_SB;
30 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_E_SB;
31 import static org.ops4j.pax.exam.CoreOptions.maven;
32 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
33 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
34 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
35
36 import com.google.common.collect.ImmutableSet;
37 import com.google.common.collect.Lists;
38 import com.google.common.collect.Sets;
39 import java.io.File;
40 import java.io.IOException;
41 import java.net.DatagramSocket;
42 import java.net.InetAddress;
43 import java.net.InetSocketAddress;
44 import java.net.SocketException;
45 import java.net.SocketTimeoutException;
46 import java.net.UnknownHostException;
47 import java.nio.ByteBuffer;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Set;
54 import javax.inject.Inject;
55 import org.junit.After;
56 import org.junit.Assert;
57 import org.junit.Before;
58 import org.junit.Test;
59 import org.junit.runner.RunWith;
60 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
61 import org.opendaylight.lispflowmapping.config.ConfigIni;
62 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
63 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
64 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
65 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
66 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
67 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
68 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
69 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
70 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
71 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
72 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
73 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
74 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
75 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop.LrsBits;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.HopBuilder;
104 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
105 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkeyBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping._record.container.MappingRecord;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping._record.container.MappingRecord.Action;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping._record.container.MappingRecordBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping._record.list.MappingRecordItem;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping._record.list.MappingRecordItemBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
143 import org.opendaylight.yangtools.yang.common.Uint16;
144 import org.opendaylight.yangtools.yang.common.Uint32;
145 import org.opendaylight.yangtools.yang.common.Uint8;
146 import org.ops4j.io.FileUtils;
147 import org.ops4j.pax.exam.Option;
148 import org.ops4j.pax.exam.junit.PaxExam;
149 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
150 import org.ops4j.pax.exam.options.MavenUrlReference;
151 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
152 import org.ops4j.pax.exam.spi.reactors.PerClass;
153 import org.ops4j.pax.exam.util.Filter;
154 import org.osgi.framework.Bundle;
155 import org.osgi.framework.BundleContext;
156 import org.osgi.framework.InvalidSyntaxException;
157 import org.slf4j.Logger;
158 import org.slf4j.LoggerFactory;
159
160 @RunWith(PaxExam.class)
161 @ExamReactorStrategy(PerClass.class)
162 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
163     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
164
165     private byte[] mapRequestPacket;
166     private byte[] mapRegisterPacketWithNotify;
167     private byte[] mapRegisterPacketWithoutNotify;
168     String lispBindAddress = "127.0.0.1";
169     static final String ourAddress = "127.0.0.2";
170     private Rloc locatorEid;
171     private DatagramSocket socket;
172     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
173
174     public static final String ODL = "org.opendaylight.controller";
175     public static final String YANG = "org.opendaylight.yangtools";
176     private static final int MULTI_SITE_SLEEP_TIME = 2;
177     private static final int MAX_NOTIFICATION_RETRYS = 20;
178     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(Uint16.ZERO).build();
179
180     // This is temporary, since the properties in the pom file are not picked up
181     @Override
182     public String getKarafDistro() {
183         return maven()
184                 .groupId("org.opendaylight.lispflowmapping")
185                 .artifactId("lispflowmapping-karaf")
186                 .versionAsInProject()
187                 .type("zip")
188                 .getURL();
189     }
190
191     @Override
192     public MavenUrlReference getFeatureRepo() {
193         return maven()
194                 .groupId("org.opendaylight.lispflowmapping")
195                 .artifactId("features-lispflowmapping")
196                 .classifier("features")
197                 .type("xml")
198                 .versionAsInProject();
199     }
200
201     @Override
202     public String getFeatureName() {
203         return "odl-lispflowmapping-msmr";
204     }
205
206     @Override
207     protected Option[] getAdditionalOptions() {
208         return new Option[] {
209                 keepRuntimeFolder(),
210                 configureConsole().ignoreLocalConsole().ignoreRemoteShell(),
211                 editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
212                         "log4j2.logger.lispflowmapping.name",
213                         "org.opendaylight.lispflowmapping"),
214                 editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
215                         "log4j2.logger.lispflowmapping.level",
216                         LogLevel.TRACE.name())
217         };
218     }
219
220     @Test
221     public void testLispFlowMappingFeatureLoad() {
222         Assert.assertTrue(true);
223     }
224
225     @After
226     public void after() {
227         if (socket != null) {
228             socket.close();
229         }
230     }
231
232     @Before
233     public void before() throws Exception {
234         File paxExamDirectory = new File("target/exam/");
235         FileUtils.delete(paxExamDirectory);
236
237         areWeReady();
238         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
239         mapService.setMappingMerge(false);
240         ConfigIni.getInstance().setSmrRetryCount(1);
241
242         socket = MappingServiceIntegrationTestUtil.initSocket(LispMessage.PORT_NUM);
243
244         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
245         // LISP(Type = 8 - Encapsulated)
246         // IP: 192.168.136.10 -> 153.16.254.1
247         // UDP: 56756
248         // LISP(Type = 1 Map-Request
249         // Record Count: 1
250         // ITR-RLOC count: 0
251         // Source EID AFI: 1
252         // Source EID 1.2.3.4
253         // Nonce: 0x3d8d2acd39c8d608
254         // ITR-RLOC AFI=1 Address=192.168.136.10
255         // Record 1: 153.16.254.1/32
256         mapRequestPacket = extractWSUdpByteArray("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 "
257                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
258                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
259                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
260                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
261                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 "
262                 + "0060   00 01 99 10 fe 01");
263
264         // IP: 192.168.136.10 -> 128.223.156.35
265         // UDP: 49289 -> 4342
266         // LISP(Type = 3 Map-Register, P=1, M=1
267         // Record Counter: 1
268         // Nonce: 0
269         // Key ID: 0x0001
270         // AuthDataLength: 20 Data:
271         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
272         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
273         // No-Action
274         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
275         // Priority/Weight: 1/100, Multicast Priority/Weight:
276         // 255/0
277         //
278
279         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(
280                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
281                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
282                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
283                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
284                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
285                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
286                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
287
288         // IP: 192.168.136.10 -> 128.223.156.35
289         // UDP: 49289 -> 4342
290         // LISP(Type = 3 Map-Register, P=1, M=1
291         // Record Counter: 1
292         // Nonce: 7
293         // Key ID: 0x0000 NO AUTHENTICATION!!
294         // AuthDataLength: 00 Data:
295         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
296         // No-Action
297         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
298         // Priority/Weight: 1/100, Multicast Priority/Weight:
299         // 255/0
300         //
301
302         mapRegisterPacketWithNotify = extractWSUdpByteArray(
303                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
304                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
305                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
306                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
307                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
308                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
309                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
310
311         // IP: 192.168.136.10 -> 128.223.156.35
312         // UDP: 49289 -> 4342
313         // LISP(Type = 3 Map-Register, P=1, M=1
314         // Record Counter: 1
315         // Nonce: 7
316         // Key ID: 0x0000 NO AUTHENTICATION!!
317         // AuthDataLength: 00 Data:
318         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
319         // No-Action
320         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
321         // Priority/Weight: 1/100, Multicast Priority/Weight:
322         // 255/0
323         //
324
325         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(
326                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
327                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
328                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
329                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
330                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
331                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
332                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
333     }
334
335     @Inject
336     private BundleContext bc;
337     //private HttpURLConnection connection;
338     protected static boolean notificationCalled;
339
340     @Inject @Filter(timeout=60000)
341     private IFlowMapping lms;
342
343     @Inject @Filter(timeout=60000)
344     private IMappingService mapService;
345
346     @Inject @Filter(timeout=10000)
347     private IConfigLispSouthboundPlugin configLispPlugin;
348
349     @Test
350     public void testSimpleUsage() throws Exception {
351         mapRequestSimple();
352         mapRegisterWithMapNotify();
353         mapRegisterWithMapNotifyAndMapRequest();
354         registerAndQuery__MAC();
355         mapRequestMapRegisterAndMapRequest();
356         mapRegisterWithAuthenticationWithoutConfiguringAKey();
357         mapRegisterWithoutMapNotify();
358     }
359
360     @Test
361     public void testLCAFs() throws Exception {
362         registerAndQuery__SrcDestLCAF();
363         registerAndQuery__SrcDestLCAFOverlap();
364         registerAndQuery__KeyValueLCAF();
365         //registerAndQuery__ListLCAF();
366         //registerAndQuery__ApplicationData();
367         //registerAndQuery__TrafficEngineering();
368         //registerAndQuery__SegmentLCAF();
369     }
370
371     @Test
372     public void testMask() throws Exception {
373         //testPasswordExactMatch();                     TODO commented because it needs NB
374         //testPasswordMaskMatch();                      TODO commented because it needs NB
375         eidPrefixLookupIPv4();
376         eidPrefixLookupIPv6();
377     }
378 /*
379     @Test
380     public void testNorthbound() throws Exception {
381         northboundAddKey();
382         northboundAddMapping();
383         northboundDeleteMapping();
384         northboundRetrieveKey();
385         northboundRetrieveMapping();
386         northboundRetrieveSourceDestKey();
387         northboundRetrieveSourceDestMapping();
388     }
389 */
390     @Test
391     public void testTimeOuts() throws Exception {
392         timedOutMappingRecord();
393         mapRequestMapRegisterAndMapRequestTestTimeout();
394         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
395     }
396
397 //    @Test
398 //    public void testNonProxy() throws Throwable {
399 //        testSimpleNonProxy();
400 //        testNonProxyOtherPort();
401 //        testRecievingNonProxyOnXtrPort();
402 //    }
403
404     @Test
405     public void testSmr() throws Exception {
406         registerQueryRegisterWithSmr();
407         //testRepeatedSmr();
408     }
409
410     @Test
411     public void testMultiSite() throws Exception {
412         testMultiSiteScenarioA();
413         testMultiSiteScenarioB();
414     }
415
416     @Test
417     public void testNbAndSbNegativePrefix() throws UnknownHostException {
418         insertMappings();
419         testGapIntersection();
420
421         insertMappings();
422         testMultipleMappings();
423     }
424
425     @Test
426     public void testExplicitSbNegativePrefixes() {
427         // https://bugs.opendaylight.org/show_bug.cgi?id=8679
428         testNegativePrefix();
429
430         // https://bugs.opendaylight.org/show_bug.cgi?id=9023
431         testPositiveMappingRemoval();
432
433         // https://bugs.opendaylight.org/show_bug.cgi?id=9037
434         testPositivePrefixOverlappingNegativePrefix_moreSpecific();
435
436         // https://bugs.opendaylight.org/show_bug.cgi?id=9116
437         testPositivePrefixOverlappingNegativePrefix_lessSpecific();
438     }
439
440     @Test
441     public void testMappingChangeCases() {
442         // Test numbers described in the below Google Sheet:
443         // https://docs.google.com/spreadsheets/d/1we3eBBilS-HoAZgtHH3jtmvq4-6lBvVX2yMgxfF48w0/edit?usp=sharing
444
445         test1nullToNB();
446         test2nullToSB();
447         test3deleteNB();
448         test4NBtoNBmoreSpecific();
449         test5NBtoNBexactMatch();
450         test6NBtoNBlessSpecific();
451         test7NBtoSBmoreSpecific();
452         test8NBtoSBexactMatch();
453         test9NBtoSBlessSpecific();
454         test10deleteSBpositive();
455         test11SBpositiveToNBmoreSpecific();
456         test12SBpositiveToNBexactMatch();
457         test13SBtoNBlessSpecific();
458         test14SBpositiveToSBmoreSpecific();
459         test15SBpositiveToSBexactMatch();
460         test16SBpositiveToSBlessSpecific();
461         test17deleteSBnegative();
462         test18SBnegativeToNBmoreSpecific();
463         test19SBnegativeToNBexactMatch();
464         test20SBnegativeToNBlessSpecific();
465         test21SBnegativeToSBmoreSpecific();
466         test22SBnegativeToSBexactMatch();
467         test23SBnegativeToSBlessSpecific();
468
469         testNbSourceDest();
470
471         testSubtree();
472     }
473
474     private void testRepeatedSmr() throws SocketTimeoutException, UnknownHostException {
475         cleanUP();
476         long timeout = ConfigIni.getInstance().getSmrTimeout();
477         ConfigIni.getInstance().setSmrRetryCount(5);
478
479         final InstanceIdType iid = new InstanceIdType(Uint32.ONE);
480         final Eid eid1 = LispAddressUtil.asIpv4Eid("1.1.1.1", 1L);
481         final Eid subscriberEid = LispAddressUtil.asIpv4Eid("2.2.2.2", 1L);
482         final int expectedSmrs1 = 2;
483         final int expectedSmrs2 = 3;
484
485         /* set auth */
486         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
487         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
488
489         /* add subscribers */
490         final String subscriberSrcRloc1 = "127.0.0.3";
491         final String subscriberSrcRloc2 = "127.0.0.4";
492         final Set<Subscriber> subscriberSet1 = Sets.newHashSet(newSubscriber(subscriberEid, subscriberSrcRloc1),
493                 newSubscriber(subscriberEid, subscriberSrcRloc2));
494         mapService.addData(MappingOrigin.Southbound, eid1, SubKeys.SUBSCRIBERS, subscriberSet1);
495
496         final SocketReader reader1 = startSocketReader(subscriberSrcRloc1, 15000);
497         final SocketReader reader2 = startSocketReader(subscriberSrcRloc2, 15000);
498         sleepForSeconds(1);
499
500         /* add mapping */
501         final MappingRecord mapping1 = new MappingRecordBuilder()
502                 .setEid(eid1).setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
503         mapService.addMapping(MappingOrigin.Northbound, eid1, null, new MappingData(mapping1));
504
505         sleepForMilliseconds((timeout * expectedSmrs1) - (timeout / 2));
506         final List<MapRequest> requests1 = processSmrPackets(reader1, subscriberSrcRloc1, expectedSmrs1);
507         final MapReply mapReply1 = lms.handleMapRequest(
508                 new MapRequestBuilder(requests1.get(0))
509                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
510                         .setItrRloc(List.of(new ItrRlocBuilder()
511                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc1)).build()))
512                         .setEidItem(List.of(new EidItemBuilder().setEid(eid1).build()))
513                         .setSmrInvoked(true)
514                         .setSmr(false).build());
515
516         // sleep to get 1 extra smr request
517         sleepForMilliseconds(timeout * 1);
518         final List<MapRequest> requests2 = processSmrPackets(reader2, subscriberSrcRloc2, expectedSmrs2);
519         final MapReply mapReply2 = lms.handleMapRequest(
520                 new MapRequestBuilder(requests2.get(0))
521                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
522                         .setItrRloc(List.of(new ItrRlocBuilder()
523                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc2)).build()))
524                         .setEidItem(List.of(new EidItemBuilder().setEid(eid1).build()))
525                         .setSmrInvoked(true)
526                         .setSmr(false).build());
527
528         sleepForSeconds(3);
529         assertEquals(expectedSmrs1, requests1.size());
530         assertEquals(expectedSmrs2, requests2.size());
531         assertEquals((long) mapReply1.getNonce(), (long) requests1.get(0).getNonce());
532         assertEquals((long) mapReply2.getNonce(), (long) requests2.get(0).getNonce());
533         assertNextBufferEmpty(reader1);
534         assertNextBufferEmpty(reader2);
535
536         reader1.stopReading();
537         reader2.stopReading();
538     }
539
540     private SocketReader startSocketReader(String address, int timeout) {
541         DatagramSocket receivingSocket = null;
542
543         try {
544             receivingSocket = new DatagramSocket(new InetSocketAddress(address, LispMessage.PORT_NUM));
545         } catch (SocketException e) {
546             LOG.error("Can't initialize socket for {}", address, e);
547         }
548         return SocketReader.startReadingInStandaloneThread(receivingSocket, timeout);
549     }
550
551     private List<MapRequest> processSmrPackets(SocketReader reader, String address, int expectedSmrs) {
552         InetAddress inetAddress = null;
553         try {
554             inetAddress = InetAddress.getByName(address);
555         } catch (UnknownHostException e) {
556             LOG.error("Unknown address {}.", address, e);
557         }
558
559         final List<MapRequest> requests = new ArrayList<>();
560         byte[][] buffers = reader.getBuffers(expectedSmrs);
561         for (byte[] buf : buffers) {
562             ByteBuffer packet = ByteBuffer.wrap(buf);
563             if (MappingServiceIntegrationTestUtil.checkType(packet, MessageType.MapRequest)) {
564                 MapRequest request = MapRequestSerializer.getInstance().deserialize(packet, inetAddress);
565                 requests.add(request);
566             }
567         }
568         return requests;
569     }
570
571     private void assertNextBufferEmpty(SocketReader socketReader) {
572         assertTrue(MultiSiteScenario.areBuffersEmpty(socketReader.getBuffers(1)));
573     }
574
575     private static Subscriber newSubscriber(Eid srcEid, String srcRlocIp) {
576         final int timeout = 5;
577         final Rloc srcRloc = LispAddressUtil.asIpv4Rloc(srcRlocIp);
578         return new Subscriber(srcRloc, srcEid, timeout);
579     }
580
581     private void testMultipleMappings() throws UnknownHostException {
582         final InstanceIdType iid = new InstanceIdType(Uint32.ONE);
583         final String prefix1 = "1.1.127.10/32"; // prefix from the intersection of NB and SB gaps
584         final String prefix2 = "1.1.200.255/32"; // prefix with existing mapping in NB
585         final String prefix3 = "1.3.255.255/32";
586
587         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
588                 new EidItemBuilder()
589                         .setEidItemId(LispAddressStringifier
590                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid)))
591                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid))
592                         .build(),
593                 new EidItemBuilder()
594                         .setEidItemId(LispAddressStringifier
595                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid)))
596                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid))
597                         .build(),
598                 new EidItemBuilder()
599                         .setEidItemId(LispAddressStringifier
600                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid)))
601                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid))
602                         .build()))
603                 .build();
604         final MapReply mapReply = lms.handleMapRequest(mapRequest);
605
606         // expected result
607         final String resultPrefix1 = "1.1.64.0";
608         final Address resultNegMapping1 = new Ipv4PrefixBinaryBuilder()
609                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix1).getAddress()))
610                 .setIpv4MaskLength(Uint8.valueOf(18)).build();
611
612         final String resultPrefix2 = "1.1.128.0";
613         final Address resultMapping2 = new Ipv4PrefixBinaryBuilder()
614                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix2).getAddress()))
615                 .setIpv4MaskLength(Uint8.valueOf(17)).build();
616
617         final String resultPrefix3 = "1.3.0.0";
618         final Address resultNegMapping3 = new Ipv4PrefixBinaryBuilder()
619                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix3).getAddress()))
620                 .setIpv4MaskLength(Uint8.valueOf(16)).build();
621
622         assertEquals(resultNegMapping1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
623                 .getAddress());
624         assertEquals(resultMapping2, mapReply.getMappingRecordItem().get(1).getMappingRecord().getEid()
625                 .getAddress());
626         assertEquals(resultNegMapping3, mapReply.getMappingRecordItem().get(2).getMappingRecord().getEid()
627                 .getAddress());
628     }
629
630     /**
631      * Tests a negative mapping from an intersection of gaps in northbound and southbound.
632      */
633     private void testGapIntersection() throws UnknownHostException {
634         // request an Eid from a gap between mappings
635         final MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "1.1.127.10/32"));
636
637         // expected negative mapping
638         final Address resultNegMapping = new Ipv4PrefixBinaryBuilder()
639                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName("1.1.64.0").getAddress()))
640                 .setIpv4MaskLength(Uint8.valueOf(18)).build();
641         assertEquals(resultNegMapping, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
642                 .getAddress());
643     }
644
645     private void testNegativePrefix() {
646         // First, we test with one mapping in NB and one mapping in SB
647         cleanUP();
648         allowNullAuthenticationForAllIPv4(1L);
649
650         insertNBMappings(1L, "192.0.2.0/24");
651         insertSBMappings(false, 1L, "10.0.0.0/32");
652
653         restartSocket();
654         sleepForSeconds(2);
655
656         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "11.1.1.1/32"));
657         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "11.0.0.0/8");
658         assertEquals(expectedNegativePrefix, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid());
659         assertTrue(MappingRecordUtil.isNegativeMapping(mapReply.getMappingRecordItem().get(0).getMappingRecord()));
660
661         // Second, we test with two mappings in NB only
662         cleanUP();
663
664         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
665
666         restartSocket();
667         sleepForSeconds(2);
668
669         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
670         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
671         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
672         assertEquals(expectedNegativePrefix, mr.getEid());
673         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
674     }
675
676     private void testPositiveMappingRemoval() {
677         cleanUP();
678         allowNullAuthenticationForAllIPv4(1L);
679
680         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
681         insertSBMappings(false, 1L, "192.168.32.0/19");
682
683         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
684         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/19");
685         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
686         assertEquals(expectedNegativePrefix, mr.getEid());
687         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
688
689         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.64.1/32"));
690         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.64.0/18");
691         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
692         assertEquals(expectedNegativePrefix, mr.getEid());
693         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
694
695         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.128.1/32"));
696         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.128.0/17");
697         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
698         assertEquals(expectedNegativePrefix, mr.getEid());
699         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
700
701         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
702
703         mapService.removeMapping(MappingOrigin.Southbound, LispAddressUtil.asIpv4PrefixBinaryEid(
704                 1L, "192.168.32.0/19"));
705
706         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
707
708         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.32.1/32"));
709         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
710         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
711         assertEquals(expectedNegativePrefix, mr.getEid());
712         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
713
714         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
715     }
716
717     private void testPositivePrefixOverlappingNegativePrefix_moreSpecific() {
718         cleanUP();
719
720         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
721
722         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
723         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
724         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
725         assertEquals(expectedNegativePrefix, mr.getEid());
726         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
727
728         insertNBMappings(1L, "192.168.1.0/24");
729         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
730
731         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
732         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/24");
733         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
734         assertEquals(expectedNegativePrefix, mr.getEid());
735         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
736     }
737
738     private void testPositivePrefixOverlappingNegativePrefix_lessSpecific() {
739         cleanUP();
740
741         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
742
743         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
744         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
745         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
746         assertEquals(expectedNegativePrefix, mr.getEid());
747         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
748
749         insertNBMappings(1L, "192.0.0.0/8");
750         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
751
752         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
753         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.0.0.0/8");
754         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
755         assertEquals(expectedPositivePrefix, mr.getEid());
756         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
757     }
758
759     /*
760      * Mapping change: NO old mapping, new mapping is from northbound
761      * Support status: SUPPORTED
762      * Description: If no mappings exists in either NB or SB, that means no subscriptions exist either, so
763      *              this is just a simple case of adding a new mapping, no SMR required.
764      */
765     private void test1nullToNB() {
766         cleanUP();
767
768         insertNBMappings(1L, "192.168.0.0/16");
769         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
770     }
771
772     /*
773      * Mapping change: NO old mapping, new mapping is from southbound
774      * Support status: SUPPORTED
775      * Description: If no mappings exists in either NB or SB, that means no subscriptions exist either, so
776      *              this is just a simple case of adding a new mapping, no SMR required.
777      */
778     private void test2nullToSB() {
779         cleanUP();
780         allowNullAuthenticationForAllIPv4(1L);
781
782         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
783         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
784     }
785
786     /*
787      * Mapping change: deleting a mapping from northbound
788      * Support status: SUPPORTED
789      * Description: When a NB mapping is deleted, its subscribers, and the subscribers of its children are notified.
790      */
791     private void test3deleteNB() {
792         cleanUP();
793         allowNullAuthenticationForAllIPv4(1L);
794
795         // Overlapping SB mapping, which will stay
796         insertSBMappings(false, 1L, "192.168.255.0/24");
797         // Subscribe to the overlapping SB mapping
798         lms.handleMapRequest(newMapRequest(1L, "192.168.255.1/32"));
799         // NB mapping which will be removed
800         insertNBMappings(1L, "192.168.0.0/16");
801         // The child prefix is notified of the change
802         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.255.0");
803         // The above SMR will result in a SMR-invoked Map-Request for 192.168.255.0/32, which in turn will result  in
804         // subscribing to the new NB mapping
805
806         // Remove NB mapping
807         removeNBMapping(1L, "192.168.0.0/16");
808         // The removed prefix and the child prefix are both notified of the change
809         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.255.0");
810     }
811
812     /*
813      * Mapping change: adding a more specific northbound mapping overlapping a less specific one
814      * Support status: PARTIALLY SUPPORTED (?)
815      * Description: Overlapping prefixes in general are not "officially" supported in NB and should not be used.
816      *              That said, adding a more specific does result in an SMR, but adding a less specific does not (see
817      *              test 6 below).
818      */
819     private void test4NBtoNBmoreSpecific() {
820         cleanUP();
821
822         // Original (less specific) NB mapping
823         insertNBMappings(1L, "192.168.0.0/16");
824         // Subscribe, by sending a Map-Request
825         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
826         // Add the more specific new overlapping mapping
827         insertNBMapping(1L, "192.168.1.0/24", "10.10.10.10");
828         // No notification is sent
829         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
830     }
831
832     /*
833      * Mapping change: updating a northbound mapping
834      * Support status: SUPPORTED
835      * Description: Simple case of updating an exact match NB prefix.
836      */
837     private void test5NBtoNBexactMatch() {
838         cleanUP();
839
840         // Original NB mapping
841         insertNBMappings(1L, "192.168.0.0/16");
842         // Subscribe, by sending a Map-Request
843         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
844         // Updated NB mapping with different locator set for the same exact prefix
845         insertNBMapping(1L, "192.168.0.0/16", "10.10.10.10");
846         // Notification is sent for the prefix
847         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
848     }
849
850     /*
851      * Mapping change: adding a less specific northbound mapping overlapping a more specific one
852      * Support status: NOT SUPPORTED
853      * Description: Overlapping prefixes in general are not "officially" supported in NB and should not be used.
854      *              That said, adding a more specific does result in an SMR (see test 4 above), but adding a less
855      *              specific does not.
856      */
857     private void test6NBtoNBlessSpecific() {
858         cleanUP();
859
860         // Original (more specific) NB mapping
861         insertNBMappings(1L, "192.168.0.0/16");
862         // Subscribe, by sending a Map-Request
863         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
864         // Add the less specific new overlapping mapping
865         insertNBMapping(1L, "192.0.0.0/8", "10.10.10.10");
866         // No notification is sent
867         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
868     }
869
870     /*
871      * Mapping change: adding a more specific southbound mapping overlapping a less specific northbound mapping
872      * Support status: SUPPORTED
873      * Description: This is not an issue for NB_FIRST, since there is no change in the resolved mappings for the
874      *              prefix range covered by the existing NB mapping. For NB_AND_SB it does make a difference, and that
875      *              case is supported.
876      */
877     private void test7NBtoSBmoreSpecific() {
878         cleanUP();
879         allowNullAuthenticationForAllIPv4(1L);
880         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
881
882         // Original (less specific) NB mapping
883         insertNBMapping(1L, "192.168.0.0/16", "172.16.0.1", "10.10.10.10");
884         // Subscribe, by sending a Map-Request
885         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
886         // Add the more specific new overlapping SB mapping
887         registerSBMapping(1L, "192.168.1.0/24", "10.10.10.10");
888         // Notification is sent for the original prefix
889         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
890     }
891
892     /*
893      * Mapping change: adding a southbound mapping matching a northbound mapping
894      * Support status: SUPPORTED
895      * Description: When a SB mapping is added that has an existing exact match NB counterpart the subscribers of the
896      *              prefix are notified. This is not strictly necessary for the NB_FIRST policy, but it is still useful
897      *              for the NB_AND_SB policy.
898      */
899     private void test8NBtoSBexactMatch() {
900         cleanUP();
901         allowNullAuthenticationForAllIPv4(1L);
902         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
903
904         // Original NB mapping
905         insertNBMapping(1L, "192.168.0.0/16", "172.16.0.1", "10.10.10.10");
906         // Subscribe, by sending a Map-Request
907         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
908         // Add a mapping with the same EID but different locator set in SB
909         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
910         // Notification is sent for the prefix
911         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
912     }
913
914     /*
915      * Mapping change: adding a less specific southbound mapping overlapping a more specific northbound mapping
916      * Support status: PARTIALLY SUPPORTED (?)
917      * Description: When a less specific SB mapping is added no SMR is sent, but for the NB mapping subscribers there
918      *              is no actual change in the mapping. Part of the southbound prefix is not covered by the existing NB,
919      *              and queries for that part will resolve to the full SB prefix, shadowing the NB prefix. This is a
920      *              general problem with overlapping prefixes, but this particular combination is pretty bad.
921      */
922     private void test9NBtoSBlessSpecific() {
923         cleanUP();
924         allowNullAuthenticationForAllIPv4(1L);
925
926         // Original (more specific) NB mapping
927         insertNBMappings(1L, "192.168.0.0/16");
928         // Subscribe, by sending a Map-Request
929         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
930         // Add the less specific new overlapping SB mapping
931         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
932         // No notification is sent
933         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
934     }
935
936     /*
937      * Mapping change: deleting a positive mapping from southbound
938      * Support status: SUPPORTED
939      * Description: When a positive SB mapping is deleted, its subscribers, and the subscribers of its children are
940      *              notified.
941      */
942     private void test10deleteSBpositive() {
943         cleanUP();
944         allowNullAuthenticationForAllIPv4(1L);
945
946         // Overlapping SB mapping, which will stay
947         insertSBMappings(false, 1L, "192.168.255.0/24");
948         // Subscribe to the overlapping SB mapping
949         lms.handleMapRequest(newMapRequest(1L, "192.168.255.1/32"));
950         // Overlapping negative mapping
951         insertSBMappings(true, 1L, "192.168.127.0/24");
952         // Subscribe to the overlapping negative SB mapping
953         lms.handleMapRequest(newMapRequest(1L, "192.168.127.1/32"));
954         // Positive SB mapping which will be removed
955         insertSBMappings(false, 1L, "192.168.0.0/16");
956         // The child prefix is notified of the change
957         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.127.0", "192.168.255.0");
958         // The above SMR will result in a SMR-invoked Map-Request for 192.168.255.0/32 and 192.168.255.0/32, which in
959         // turn will result  in subscribing to the new SB mapping
960
961         // Remove positive SB mapping
962         removeSBMapping(1L, "192.168.0.0/16");
963         // The removed prefix and the child prefix are both notified of the change
964         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.255.0");
965     }
966
967     /*
968      * Mapping change: adding a more specific northbound mapping overlapping a less specific southbound mapping
969      * Support status: PARTIALLY SUPPORTED (?)
970      * Description: This mapping change is detected and an SMR is sent, but the EID prefix in it is for the base address
971      *              of the old prefix. When xTRs query for that, they won't actually install the new mapping. This is
972      *              one of those cases where saving the original request causing the subscription would help the xTR get
973      *              the correct mapping. Additionally, similar to case 9 above, this combination will shadow the NB
974      *              mapping for new requests into the non-overlapping part.
975      */
976     private void test11SBpositiveToNBmoreSpecific() {
977         cleanUP();
978         allowNullAuthenticationForAllIPv4(1L);
979
980         // Original (less specific) SB mapping
981         insertSBMappings(false, 1L, "192.168.0.0/16");
982         // Subscribe, by sending a Map-Request
983         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
984         // Add the more specific new overlapping NB mapping
985         insertNBMappings(1L, "192.168.1.0/24");
986         // Notification is sent for the original prefix
987         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
988     }
989
990     /*
991      * Mapping change: adding a northbound mapping matching a southbound mapping
992      * Support status: SUPPORTED
993      * Description: When a NB mapping is added that has an existing exact match SB counterpart, the subscribers of the
994      *              prefix are notified.
995      */
996     private void test12SBpositiveToNBexactMatch() {
997         cleanUP();
998         allowNullAuthenticationForAllIPv4(1L);
999
1000         // Original SB mapping
1001         insertSBMappings(false, 1L, "192.168.0.0/16");
1002         // Subscribe, by sending a Map-Request
1003         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1004         // Add a mapping with the same EID but different locator set in NB
1005         insertNBMappings(1L, "192.168.0.0/16");
1006         // Notification is sent for the prefix
1007         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1008     }
1009
1010     /*
1011      * Mapping change: adding a less specific northbound mapping overlapping a more specific southbound mapping
1012      * Support status: PARTIALLY SUPPORTED (?)
1013      * Description: No SMR is sent, but the NB mapping takes precedence for new requests.
1014      */
1015     private void test13SBtoNBlessSpecific() {
1016         cleanUP();
1017         allowNullAuthenticationForAllIPv4(1L);
1018
1019         // Original (more specific) SB mapping
1020         insertNBMappings(1L, "192.168.0.0/16");
1021         // Subscribe, by sending a Map-Request
1022         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1023         // Add the less specific new overlapping SB mapping
1024         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1025         // No notification is sent
1026         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
1027     }
1028
1029     /*
1030      * Mapping change: adding a more specific southbound mapping overlapping a less specific one
1031      * Support status: SUPPORTED
1032      * Description: When a more specific SB mapping is added, the subscribers of the overlapping less specific existing
1033      *              SB mapping are notified.
1034      */
1035     private void test14SBpositiveToSBmoreSpecific() {
1036         cleanUP();
1037         allowNullAuthenticationForAllIPv4(1L);
1038
1039         insertSBMappings(false, 1L, "192.168.0.0/16");
1040
1041         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1042         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1043         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1044         assertEquals(expectedPositivePrefix, mr.getEid());
1045         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1046
1047         registerSBMapping(1L, "192.168.254.0/24", "10.10.10.10");
1048         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1049
1050         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1051         expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1052         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1053         assertEquals(expectedPositivePrefix, mr.getEid());
1054         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1055
1056         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.254.1/32"));
1057         expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.254.0/24");
1058         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1059         assertEquals(expectedPositivePrefix, mr.getEid());
1060         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1061     }
1062
1063     /*
1064      * Mapping change: updating a southbound mapping
1065      * Support status: SUPPORTED
1066      * Description: Simple case of updating an exact match SB prefix.
1067      */
1068     private void test15SBpositiveToSBexactMatch() {
1069         cleanUP();
1070         allowNullAuthenticationForAllIPv4(1L);
1071
1072         // Original SB mapping
1073         insertSBMappings(false, 1L, "192.168.0.0/16");
1074         // Subscribe, by sending a Map-Request
1075         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1076         // Updated SB mapping with different locator set for the same exact prefix
1077         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1078         // Notification is sent for the prefix
1079         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1080     }
1081
1082     /*
1083      * Mapping change: adding a less specific southbound mapping overlapping a more specific one
1084      * Support status: SUPPORTED
1085      * Description: When a less specific SB mapping is added, all child prefixes with subscribers are notified.
1086      */
1087     private void test16SBpositiveToSBlessSpecific() {
1088         cleanUP();
1089         allowNullAuthenticationForAllIPv4(1L);
1090
1091         // Original (more specific) SB mapping
1092         insertSBMappings(false, 1L, "192.168.0.0/16");
1093         // Subscribe, by sending a Map-Request
1094         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1095         // Add the less specific new overlapping SB mapping
1096         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1097         // Notification is sent for the original prefix
1098         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1099     }
1100
1101     /*
1102      * Mapping change: deleting a negative mapping from southbound
1103      * Support status: SUPPORTED
1104      * Description: When a negative SB mapping is deleted, its subscribers are notified.
1105      */
1106     private void test17deleteSBnegative() {
1107         cleanUP();
1108         allowNullAuthenticationForAllIPv4(1L);
1109
1110         // First we add two negative mappings to NB with a hole between them
1111         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1112         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1113         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1114         // Remove positive SB mapping
1115         removeSBMapping(1L, "192.168.0.0/16");
1116         // Notification is sent for the prefix
1117         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1118     }
1119
1120     /*
1121      * Mapping change: adding a more specific northbound mapping overlapping a less specific negative southbound mapping
1122      * Support status: SUPPORTED
1123      * Description: When a more specific NB mapping is added, the overlapping negative prefix is deleted, its
1124      *              subscribers notified, and then more specific negatives are created when requested.
1125      */
1126     private void test18SBnegativeToNBmoreSpecific() {
1127         cleanUP();
1128
1129         // First we add two negative mappings to NB with a hole between them
1130         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1131         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1132         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1133         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1134         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1135         assertEquals(expectedNegativePrefix, mr.getEid());
1136         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1137
1138         // Add the more specific new overlapping NB mapping
1139         insertNBMappings(1L, "192.168.1.0/24");
1140         // Notification is sent for the original prefix
1141         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1142
1143         // The original negative should now be broken up
1144         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1145         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/24");
1146         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1147         assertEquals(expectedNegativePrefix, mr.getEid());
1148         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1149
1150         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.64.1/32"));
1151         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.64.0/18");
1152         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1153         assertEquals(expectedNegativePrefix, mr.getEid());
1154         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1155
1156         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.1.1/32"));
1157         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.1.0/24");
1158         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1159         assertEquals(expectedPositivePrefix, mr.getEid());
1160         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1161     }
1162
1163     /*
1164      * Mapping change: adding a northbound mapping matching a negative southbound mapping
1165      * Support status: SUPPORTED
1166      * Description: When a NB mapping is added that has an existing exact match negative SB counterpart,
1167      *              the subscribers of the prefix are notified, and the negative is deleted.
1168      */
1169     private void test19SBnegativeToNBexactMatch() {
1170         cleanUP();
1171
1172         // First we add two negative mappings to NB with a hole between them
1173         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1174         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1175         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1176         insertNBMappings(1L, "192.168.0.0/16");
1177         // Notification is sent for the prefix
1178         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.0.0");
1179     }
1180
1181     /*
1182      * Mapping change: adding a less specific northbound mapping overlapping a more specific negative southbound mapping
1183      * Support status: PARTIALLY SUPPORTED (?)
1184      * Description: When a less specific NB mapping covering a more specific negative SB mapping is added, the negative
1185      *              is deleted and its subscribers notified. Depending on the particular xTR map-cache implementation,
1186      *              the negative prefix may or may not stay cached (hence partially supported).
1187      */
1188     private void test20SBnegativeToNBlessSpecific() {
1189         cleanUP();
1190         allowNullAuthenticationForAllIPv4(1L);
1191
1192         // Add a negative mapping
1193         insertSBMappings(true, 1L, "192.168.0.0/16");
1194         // Subscribe for the mapping
1195         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1196         // Add less specific northbound mapping
1197         insertNBMappings(1L, "192.0.0.0/8");
1198         // Notification is sent for the negative prefix
1199         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1200     }
1201
1202     /*
1203      * Mapping change: adding a more specific southbound mapping overlapping a less specific negative mapping
1204      * Support status: SUPPORTED
1205      * Description: When a more specific SB mapping is added, the subscribers of the overlapping less specific existing
1206      *              negative SB mapping are notified, the negative is deleted, and then more specific negatives are
1207      *              created when requested.
1208      */
1209     private void test21SBnegativeToSBmoreSpecific() {
1210         cleanUP();
1211         allowNullAuthenticationForAllIPv4(1L);
1212
1213         // First we add two negative mappings to NB with a hole between them
1214         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1215         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1216         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1217         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1218         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1219         assertEquals(expectedNegativePrefix, mr.getEid());
1220         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1221
1222         // Add the more specific new overlapping SB mapping
1223         registerSBMapping(1L, "192.168.254.0/24", "10.10.10.10");
1224         // Notification is sent for the original prefix
1225         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L,"192.168.0.0");
1226
1227         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1228         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/17");
1229         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1230         assertEquals(expectedNegativePrefix, mr.getEid());
1231         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1232
1233         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.254.1/32"));
1234         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.254.0/24");
1235         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1236         assertEquals(expectedPositivePrefix, mr.getEid());
1237         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1238     }
1239
1240     /*
1241      * Mapping change: updating a negative southbound mapping with a positive one
1242      * Support status: SUPPORTED
1243      * Description: Simple case of updating an exact match SB prefix.
1244      */
1245     private void test22SBnegativeToSBexactMatch() {
1246         cleanUP();
1247         allowNullAuthenticationForAllIPv4(1L);
1248
1249         // First we add two negative mappings to NB with a hole between them
1250         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1251         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1252         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1253         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1254         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1255         assertEquals(expectedNegativePrefix, mr.getEid());
1256         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1257         // Updated SB mapping with different locator set for the same exact prefix
1258         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1259         // Notification is sent for the prefix
1260         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1261
1262         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1263         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1264         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1265         assertEquals(expectedPositivePrefix, mr.getEid());
1266         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1267     }
1268
1269     /*
1270      * Mapping change: adding a less specific southbound mapping overlapping a more specific negative mapping
1271      * Support status: SUPPORTED
1272      * Description: When a less specific SB mapping is added, all child prefixes with subscribers are notified. In this
1273      *              case, the overlapping more specific negative is removed.
1274      */
1275     private void test23SBnegativeToSBlessSpecific() {
1276         cleanUP();
1277         allowNullAuthenticationForAllIPv4(1L);
1278
1279         // Add a negative mapping
1280         insertSBMappings(true, 1L, "192.168.0.0/16");
1281         // Subscribe for the mapping
1282         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1283         // Add less specific southbound mapping
1284         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1285         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1286     }
1287
1288     private void testNbSourceDest() {
1289         cleanUP();
1290
1291         insertNBMappingSourceDest(1L, "192.0.2.0/24", "192.168.0.0/16",
1292                 MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC_STRING);
1293
1294         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1295         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1296         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1297         assertEquals(expectedPositivePrefix, mr.getEid());
1298         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1299
1300         insertNBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1301         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1302     }
1303
1304     private void testSubtree() {
1305         cleanUP();
1306         allowNullAuthenticationForAllIPv4(1L);
1307
1308         insertSBMappings(false, 1L, "10.0.0.0/8",
1309                 "10.0.0.0/16", "10.2.0.0/16", "10.255.0.0/16");
1310         Eid queryPrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.0.0.0/9");
1311         Set<Eid> subtreePrefixes = mapService.getSubtree(MappingOrigin.Southbound, queryPrefix);
1312         LOG.debug("Subtree prefix set for EID {}: {}", LispAddressStringifier.getString(queryPrefix),
1313                 LispAddressStringifier.getString(subtreePrefixes));
1314         Set<Eid> expectedSubtreePrefixes = new HashSet<>();
1315         expectedSubtreePrefixes.add(LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.0.0.0/16"));
1316         expectedSubtreePrefixes.add(LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.2.0.0/16"));
1317         assertEquals(expectedSubtreePrefixes, subtreePrefixes);
1318     }
1319
1320     private void insertMappings() {
1321         cleanUP();
1322         allowNullAuthenticationForAllIPv4(1L);
1323         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
1324
1325         insertNBMappings(1L, "1.2.0.0/16", "1.1.128.0/17");
1326         insertSBMappings(false, 1L, "1.1.32.0/19", "1.0.0.0/8");
1327
1328         restartSocket();
1329         sleepForSeconds(2);
1330     }
1331
1332     private void insertNBMappings(long iid, String ... prefixes) {
1333         LOG.debug("Adding Northbound mappings in VNI {} for prefixes: {}", iid, prefixes);
1334         final InstanceIdType iiType = new InstanceIdType(Uint32.valueOf(iid));
1335         for (String prefix : prefixes) {
1336             MappingRecord record = newMappingRecord(prefix, iiType);
1337             mapService.addMapping(MappingOrigin.Northbound, record.getEid(), null, new MappingData(record));
1338         }
1339         sleepForMilliseconds(100);
1340         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1341     }
1342
1343     private void removeNBMapping(long iid, String prefix) {
1344         LOG.debug("Removing Northbound mapping in VNI {} for prefix {}", iid, prefix);
1345         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1346         mapService.removeMapping(MappingOrigin.Northbound, eid);
1347     }
1348
1349     private void insertNBMapping(long iid, String prefix, String ... locators) {
1350         LOG.debug("Adding Northbound mapping in VNI {} for prefix {}, locators {}", iid, prefix, locators);
1351         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1352         List<Rloc> rlocs = new ArrayList<>();
1353         for (String locator : locators) {
1354             rlocs.add(LispAddressUtil.asIpv4Rloc(locator));
1355         }
1356         insertNBMapping(eid, rlocs);
1357     }
1358
1359     private void insertNBMappingSourceDest(long iid, String src, String dst, String locator) {
1360         String srcAddress = MaskUtil.getPrefixAddress(src);
1361         String dstAddress = MaskUtil.getPrefixAddress(dst);
1362         int srcMask = Integer.parseInt(MaskUtil.getPrefixMask(src));
1363         int dstMask = Integer.parseInt(MaskUtil.getPrefixMask(dst));
1364         LOG.debug("Adding Northbound mapping in VNI {} for prefix {}|{}, locator {}", iid, src, dst, locator);
1365         Eid eid = LispAddressUtil.asSrcDstEid(srcAddress, dstAddress, srcMask, dstMask, iid);
1366         List<Rloc> rlocs = Arrays.asList(LispAddressUtil.asIpv4Rloc(locator));
1367         insertNBMapping(eid, rlocs);
1368     }
1369
1370     private void insertNBMapping(Eid eid, List<Rloc> rlocs) {
1371         MappingRecord record = MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(eid, rlocs).build();
1372         mapService.addMapping(MappingOrigin.Northbound, record.getEid(), null, new MappingData(record));
1373         sleepForMilliseconds(100);
1374         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1375     }
1376
1377     private void allowNullAuthenticationForAllIPv4(long iid) {
1378         final InstanceIdType iiType = new InstanceIdType(Uint32.valueOf(iid));
1379         Eid allIPs = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iiType);
1380         mapService.addAuthenticationKey(allIPs, NULL_AUTH_KEY);
1381     }
1382
1383     private void insertSBMappings(boolean negative, long iid, String... prefixes) {
1384         LOG.debug("Adding Southbound mappings in VNI {} for prefixes: {}", iid, prefixes);
1385         final InstanceIdType iiType = new InstanceIdType(Uint32.valueOf(iid));
1386
1387         for (String prefix : prefixes) {
1388             MappingRecord record;
1389             if (negative) {
1390                 record = newMappingRecordNegative(prefix, iiType);
1391             } else {
1392                 record = newMappingRecord(prefix, iiType);
1393             }
1394             mapService.addMapping(MappingOrigin.Southbound, record.getEid(), null,
1395                     new MappingData(record, System.currentTimeMillis()));
1396         }
1397         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1398     }
1399
1400     private void registerSBMapping(long iid, String prefix, String locator) {
1401         LOG.debug("Registering Southbound mapping in VNI {} for prefix {}, locator {}" +
1402                 " via simulated Map-Register a.k.a. handleMapRegister()", iid, prefix, locator);
1403
1404         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1405         Rloc rloc = LispAddressUtil.asIpv4Rloc(locator);
1406         MapRegister mr = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid, rloc).build();
1407         lms.handleMapRegister(mr);
1408         sleepForMilliseconds(100);
1409         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1410     }
1411
1412     private void removeSBMapping(long iid, String prefix) {
1413         LOG.debug("Removing Southbound mapping in VNI {} for prefix {}", iid, prefix);
1414         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1415         mapService.removeMapping(MappingOrigin.Southbound, eid);
1416     }
1417
1418     private MappingRecord newMappingRecord(String prefix, InstanceIdType iid) {
1419         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
1420         return MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(prefixBinary).build();
1421     }
1422
1423     private MappingRecord newMappingRecordNegative(String prefix, InstanceIdType iid) {
1424         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
1425         return MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(prefixBinary, (List<Rloc>) null)
1426                 .setAction(Action.NativelyForward).build();
1427     }
1428
1429     private MapRequest newMapRequest(long iid, String prefix) {
1430         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, new InstanceIdType(Uint32.valueOf(iid)));
1431         return MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(prefixBinary).build();
1432     }
1433
1434     /**
1435      * TEST SCENARIO A
1436      */
1437     public void testMultiSiteScenarioA() throws IOException {
1438         cleanUP();
1439         ConfigIni.getInstance().setSmrRetryCount(1);
1440         ConfigIni.getInstance().setSmrTimeout(30000L);
1441
1442         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
1443         multiSiteScenario.setCommonAuthentication();
1444
1445         restartSocket();
1446         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
1447
1448         //TEST CASE 1
1449         multiSiteScenario.storeSouthboundMappings(false, SITE_A, SITE_B, SITE_C, SITE_D4, SITE_D5);
1450         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
1451         multiSiteScenario.storeNorthMappingNegative(SITE_C_NEGATIVE, Action.Drop);
1452         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1453         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1454         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1455         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1456
1457         //TEST CASE 2
1458         //following action should trigger generating of SMR messages:
1459         // 1) 192.0.2.5/32
1460         // 2) 192.0.1.1/32
1461         multiSiteScenario.storeNorthMappingSrcDst(SITE_A, SITE_C);
1462         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1463         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1));
1464         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
1465         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1466         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
1467
1468         //TEST CASE 3
1469         // following action should trigger generating of SMR messages:
1470         // 1) 192.0.2.5/32
1471         // 2) 192.0.1.1/32
1472         // 3) 192.0.1.5/32
1473         // 4) 192.0.4.5/32
1474         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
1475         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1476         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1), SITE_A
1477                         .getHost(5),
1478                 SITE_D4.getHost(5));
1479         multiSiteScenario.assertPingWorks(SITE_D4, 5, SITE_C, 4);
1480
1481         //TEST CASE 4
1482         // following action should trigger generating of SMR messages:
1483         // 1) 192.0.2.5/32
1484         // 2) 192.0.1.1/32
1485         // 3) 192.0.1.5/32
1486         // 4) 192.0.4.5/32
1487         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C_RLOC_10);
1488         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1489         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
1490                 SITE_A.getHost(5), SITE_D4.getHost(5));
1491         //way of testing ping - get RLOC for mapping src-dst and compare it with awaited value doesn't test
1492         //that ping won't be successfull
1493         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
1494
1495         //TEST CASE 5
1496         // following action should trigger generating of SMR messages:
1497         // 1) 192.0.2.5/32
1498         // 2) 192.0.1.1/32
1499         // 3) 192.0.1.5/32
1500         // 4) 192.0.4.5/32
1501         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
1502         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1503         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
1504                 SITE_A.getHost(5), SITE_D4.getHost(5));
1505         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
1506
1507         //TEST CASE 6
1508         multiSiteScenario.assertPingFails(SITE_D5, 5, SITE_C, 3);
1509
1510         //TEST CASE 7
1511         // following action should trigger generating of SMR messages:
1512         // 1) 192.0.4.5/32
1513         // 2) 192.0.2.5/32
1514         // 3) 192.0.5.5/32
1515         // 4) 192.0.1.5/32
1516         // 5) 192.0.1.1/32
1517         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A, SITE_C);
1518         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1519         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1520                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1521
1522         // following action should trigger generating of SMR messages:
1523         // 1) 192.0.4.5/32
1524         // 2) 192.0.2.5/32
1525         // 3) 192.0.5.5/32
1526         // 4) 192.0.1.5/32
1527         // 5) 192.0.1.1/32
1528         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
1529         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1530         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1531                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1532
1533         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1534         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1535         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1536
1537         //TEST CASE 8
1538         // following action should trigger generating of SMR messages:
1539         // 1) 192.0.4.5/32
1540         // 2) 192.0.2.5/32
1541         // 3) 192.0.5.5/32
1542         // 4) 192.0.1.5/32
1543         // 5) 192.0.1.1/32
1544         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B, SITE_C);
1545         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1546         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1547                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1548         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1549         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
1550         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1551
1552         //TEST CASE 9
1553         // following action should trigger generating of SMR messages:
1554         // 1) 192.0.4.5/32
1555         // 2) 192.0.2.5/32
1556         // 3) 192.0.5.5/32
1557         // 4) 192.0.1.5/32
1558         // 5) 192.0.1.1/32
1559         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
1560         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1561         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1562                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1563         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1564         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1565         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
1566
1567         socketReader.stopReading();
1568
1569     }
1570
1571     /**
1572      * TEST SCENARIO B
1573      */
1574     public void testMultiSiteScenarioB() throws IOException {
1575         restartSocket();
1576         cleanUP();
1577
1578         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
1579         multiSiteScenario.setCommonAuthentication();
1580
1581         restartSocket();
1582         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
1583
1584         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
1585         mapService.setMappingMerge(true);
1586
1587         //TEST CASE 1
1588         multiSiteScenario.storeSouthboundMappings(true, SITE_A_SB, SITE_B_SB, SITE_C_WP_100_1_SB, SITE_D_WP_100_1_SB,
1589                 SITE_E_SB);
1590         multiSiteScenario.storeNorthMappingIpPrefix(SITE_A_SB);
1591         multiSiteScenario.storeNorthMappingIpPrefix(SITE_B_SB);
1592         multiSiteScenario.storeNorthMappingIpPrefix(SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1593         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1594         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1595         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1596
1597         //TEST CASE 2
1598         // following action should trigger generating of SMR messages:
1599         // 1) 192.0.2.5/32
1600         // 2) 192.0.1.5/32
1601         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1602         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1603         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1604
1605         // following action should trigger generating of SMR messages:
1606         // 1) 192.0.2.5/32
1607         // 2) 192.0.1.5/32
1608         multiSiteScenario.storeNorthMappingNegative(SITE_C_SB, Action.Drop);
1609         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1610         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1611
1612         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1613         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_SB, 4);
1614
1615
1616         //TEST CASE 3
1617         // following action should trigger generating of SMR messages:
1618         // 1) 192.0.2.5/32
1619         // 2) 192.0.1.5/32
1620         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
1621         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1622         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1623         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4);
1624
1625         //TEST CASE 4
1626         multiSiteScenario.storeNorthMappingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1627         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1628         // following action should trigger generating of SMR messages:
1629         // 1) 192.0.2.5/32
1630         // 2) 192.0.1.5/32
1631         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1632         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1633
1634         //TEST CASE 5
1635         multiSiteScenario.deleteSouthboundMappings(SITE_D_DELETE_SB);
1636         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1637         // following action should trigger generating of SMR messages:
1638         // 1) 192.0.2.5/32
1639         // 2) 192.0.1.5/32
1640         //multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1641
1642         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
1643
1644         //TEST CASE 6
1645         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
1646         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1647         // following action should trigger generating of SMR messages:
1648         // 1) 192.0.2.5/32
1649         // 2) 192.0.1.5/32
1650         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1651
1652         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB);
1653         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1654         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
1655
1656         socketReader.stopReading();
1657
1658     }
1659
1660     // ------------------------------- Simple Tests ---------------------------
1661
1662     public void mapRequestSimple() throws SocketTimeoutException {
1663         cleanUP();
1664
1665         // This Map-Request is sent from a source port different from 4342
1666         // We close and bind the socket on the correct port
1667         if (socket != null) {
1668             socket.close();
1669         }
1670         socket = MappingServiceIntegrationTestUtil.initSocket(56756);
1671
1672         sendPacket(mapRequestPacket);
1673         MapReply reply = receiveMapReply();
1674         assertEquals(4435248268955932168L, reply.getNonce().longValue());
1675         restartSocket();
1676     }
1677
1678     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
1679         cleanUP();
1680         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1681
1682         sleepForSeconds(2);
1683         sendPacket(mapRegisterPacketWithNotify);
1684         MapNotify reply = receiveMapNotify();
1685         assertEquals(7, reply.getNonce().longValue());
1686     }
1687
1688     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
1689         cleanUP();
1690         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1691
1692         MapReply mapReply = registerAddressAndQuery(eid);
1693
1694         assertEquals(4, mapReply.getNonce().longValue());
1695         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
1696                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1697
1698     }
1699
1700     public void registerAndQuery__MAC() throws SocketTimeoutException {
1701         cleanUP();
1702         String macAddress = "01:02:03:04:05:06";
1703
1704         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
1705
1706         assertTrue(true);
1707         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1708         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
1709         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
1710
1711         assertEquals(macAddress, macAddressFromReply);
1712     }
1713
1714     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
1715         cleanUP();
1716         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1717         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1718         sleepForSeconds(1);
1719
1720         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
1721         sendMapRequest(mapRequest);
1722         MapReply mapReply = receiveMapReply();
1723         assertEquals(4, mapReply.getNonce().longValue());
1724         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
1725         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
1726         sendMapRegister(mapRegister);
1727         MapNotify mapNotify = receiveMapNotify();
1728         assertEquals(8, mapNotify.getNonce().longValue());
1729         sleepForSeconds(1);
1730         sendMapRequest(mapRequest);
1731         mapReply = receiveMapReply();
1732         assertEquals(4, mapReply.getNonce().longValue());
1733         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
1734                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1735
1736     }
1737
1738     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
1739         cleanUP();
1740         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1741         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1742         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1743         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1744         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1745         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1746         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1747         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1748                 .getRloc());
1749         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
1750                 .getRloc());
1751     }
1752
1753     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
1754         cleanUP();
1755         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1756         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1757         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1758         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1759         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1760         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1761         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1762         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1763                 .getRloc());
1764     }
1765
1766     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
1767         cleanUP();
1768         mapService.setMappingMerge(false);
1769         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1770         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1771         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1772         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1773         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1774         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1775                 .getRloc());
1776     }
1777
1778     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
1779         cleanUP();
1780         mapService.setMappingMerge(true);
1781         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1782         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1783         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1784         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1785         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1786         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1787                 .get(0).getRloc();
1788         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1789                 .get(1).getRloc();
1790         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
1791                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
1792     }
1793
1794     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
1795             throws SocketTimeoutException {
1796         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1797         sleepForSeconds(1);
1798         MapRegister mb = createMapRegister(eid, rloc1);
1799         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
1800         MapRequest mr = createMapRequest(eid);
1801         MapReply mapReply = lms.handleMapRequest(mr);
1802         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
1803                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1804         mb = createMapRegister(eid, rloc2);
1805         mapNotify = lms.handleMapRegister(mb).getLeft();
1806         assertEquals(8, mapNotify.getNonce().longValue());
1807         mr = createMapRequest(eid);
1808         sendMapRequest(mr);
1809         mapReply = lms.handleMapRequest(mr);
1810         return mapReply;
1811     }
1812
1813     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
1814         cleanUP();
1815         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
1816         try {
1817             receivePacket(3000);
1818             // If didn't timeout then fail:
1819             fail();
1820         } catch (SocketTimeoutException ste) {
1821         }
1822     }
1823
1824     public void mapRegisterWithoutMapNotify() {
1825         cleanUP();
1826         sendPacket(mapRegisterPacketWithoutNotify);
1827         try {
1828             receivePacket(3000);
1829             // If didn't timeout then fail:
1830             fail();
1831         } catch (SocketTimeoutException ste) {
1832         }
1833     }
1834
1835     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
1836         cleanUP();
1837         lms.setShouldUseSmr(true);
1838         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1839         sleepForSeconds(1);
1840
1841         sendPacket(mapRegisterPacketWithNotify);
1842         receiveMapNotify();
1843
1844         sleepForSeconds(1);
1845         sendPacket(mapRequestPacket);
1846         sleepForSeconds(1);
1847
1848         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
1849         sendPacket(mapRegisterPacketWithoutNotify);
1850
1851         MapRequest smr = receiveMapRequest();
1852         assertTrue(smr.getSmr());
1853         Eid sourceEid = smr.getSourceEid().getEid();
1854         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
1855         Eid smrEid = smr.getEidItem().get(0).getEid();
1856         assertTrue(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32").equals(smrEid));
1857     }
1858
1859     // --------------------- Northbound Tests ---------------------------
1860 /*
1861     private void northboundAddKey() throws Exception {
1862         cleanUP();
1863         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
1864         int mask = 32;
1865         String pass = "asdf";
1866
1867         URL url = createPutURL("key");
1868         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
1869         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
1870
1871         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
1872
1873         // Check stored password matches the one sent
1874         assertEquals(pass, retrievedKey);
1875
1876     }
1877
1878     private void northboundRetrieveSourceDestKey() throws Exception {
1879         cleanUP();
1880         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1881                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1882                 .primitiveaddress.Ipv4) LispAddressUtil
1883                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1884         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1885                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1886                 .primitiveaddress.Ipv4) LispAddressUtil
1887                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1888         int mask1 = 32;
1889         int mask2 = 32;
1890         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1891                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1892                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1893                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
1894                 .setSrcMaskLength((short) mask1)
1895                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
1896                 .setDstMaskLength((short) mask2).build();
1897         String pass = "asdf";
1898
1899         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
1900
1901         // URL url = createGetKeyIPv4URL(address1, mask1);
1902         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
1903                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
1904                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
1905                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
1906                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
1907         String reply = callURL("GET", null, "application/json", null, url);
1908         JSONTokener jt = new JSONTokener(reply);
1909         JSONObject json = new JSONObject(jt);
1910
1911         // test that the password matches what was we expected.
1912         assertEquals(pass, json.get("key"));
1913
1914     }
1915
1916     private void northboundRetrieveKey() throws Exception {
1917         cleanUP();
1918         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1919         int mask = 32;
1920         String pass = "asdf";
1921
1922         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
1923
1924         URL url = createGetKeyIPv4URL(address, mask);
1925         String reply = callURL("GET", null, "application/json", null, url);
1926         JSONTokener jt = new JSONTokener(reply);
1927         JSONObject json = new JSONObject(jt);
1928
1929         // test that the password matches what was we expected.
1930         assertEquals(pass, json.get("key"));
1931
1932     }
1933
1934     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
1935         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
1936                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
1937     }
1938
1939     private void northboundAddMapping() throws Exception {
1940         cleanUP();
1941         String pass = "asdf";
1942         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1943         int mask = 32;
1944         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1945
1946         // NB add mapping always checks the key
1947         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
1948
1949         URL url = createPutURL("mapping");
1950         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
1951         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
1952
1953         // Retrieve the RLOC from the database
1954         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1955         mapRequestBuilder.setPitr(false);
1956         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1957         mapRequestBuilder.getEidItem().add(
1958                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
1959                 LispAddressUtil.toContainer(eid)).build());
1960         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
1961
1962         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
1963                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1964                 .getLispAddressContainer());
1965
1966         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
1967
1968     }
1969
1970     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
1971         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
1972                 + "\"proxyMapReply\" : false, "
1973                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
1974                 + "{ " + "\"ipAddress\" : \""
1975                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
1976                 + "\"mapVersion\" : 0,"
1977                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
1978                 + "\"multicastPriority\" : 1,"
1979                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
1980                 + "\"afi\" : "
1981                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
1982                 + "\"rlocProbed\" : false, "
1983                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
1984                 + "\"recordTtl\" : 100" + "} " + "], "
1985                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
1986
1987         return jsonString;
1988     }
1989
1990     private void northboundRetrieveMapping() throws Exception {
1991         cleanUP();
1992         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1993         int mask = 32;
1994         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1995         // Insert mapping in the database
1996         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1997         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1998         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1999         etlr.setMaskLength((short) mask);
2000         etlr.setRecordTtl(254);
2001         etlr.setAuthoritative(false);
2002         etlr.setAction(Action.NoAction);
2003         LocatorRecordBuilder record = new LocatorRecordBuilder();
2004         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2005         record.setRouted(true);
2006         record.setRlocProbed(false);
2007         record.setLocalLocator(false);
2008         record.setPriority((short) 1);
2009         record.setWeight((short) 50);
2010         record.setMulticastPriority((short) 1);
2011         record.setMulticastWeight((short) 1);
2012         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2013         etlr.getLocatorRecord().add(record.build());
2014         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2015         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2016         lms.handleMapRegister(mapRegister.build());
2017
2018         // Get mapping using NB interface. No IID used
2019         URL url = createGetMappingIPv4URL(0, eid, mask);
2020         String reply = callURL("GET", null, "application/json", null, url);
2021         JSONTokener jt = new JSONTokener(reply);
2022         JSONObject json = new JSONObject(jt);
2023
2024         // With just one locator, locators is not a JSONArray
2025         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
2026                 .getString("ipAddress");
2027
2028         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
2029
2030     }
2031
2032     private void northboundDeleteMapping() throws Exception {
2033         cleanUP();
2034         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
2035         int mask = 32;
2036         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
2037         // Insert mapping in the database
2038         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2039         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2040         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
2041         etlr.setMaskLength((short) mask);
2042         etlr.setRecordTtl(254);
2043         etlr.setAuthoritative(false);
2044         etlr.setAction(Action.NoAction);
2045         LocatorRecordBuilder record = new LocatorRecordBuilder();
2046         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2047         record.setRouted(true);
2048         record.setRlocProbed(false);
2049         record.setLocalLocator(false);
2050         record.setPriority((short) 1);
2051         record.setWeight((short) 50);
2052         record.setMulticastPriority((short) 1);
2053         record.setMulticastWeight((short) 1);
2054         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2055         etlr.getLocatorRecord().add(record.build());
2056         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2057         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2058         lms.handleMapRegister(mapRegister.build());
2059
2060         // Delete mapping using NB interface. No IID used
2061         URL url = createDeleteMappingIPv4URL(0, eid, mask);
2062         String reply = callURL("DELETE", null, "application/json", null, url);
2063
2064         // Get mapping using NB interface. No IID used
2065         url = createGetMappingIPv4URL(0, eid, mask);
2066         reply = callURL("GET", null, "application/json", null, url);
2067         JSONTokener jt = new JSONTokener(reply);
2068         JSONObject json = new JSONObject(jt);
2069
2070         // With just one locator, locators is not a JSONArray
2071         assertEquals(json.getJSONArray("locators").length(), 0);
2072     }
2073
2074     private void northboundRetrieveSourceDestMapping() throws Exception {
2075         cleanUP();
2076         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
2077                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
2078                 .primitiveaddress.Ipv4) LispAddressUtil
2079                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
2080         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
2081                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
2082                 .primitiveaddress.Ipv4) LispAddressUtil
2083                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
2084         int mask1 = 32;
2085         int mask2 = 32;
2086         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
2087                 AddressFamilyNumberEnum.LCAF.getIanaCode())
2088                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
2089                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
2090                         address1).build()).setSrcMaskLength((short) mask1)
2091                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
2092                         address2).build()).setDstMaskLength((short) mask2).build();
2093         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
2094
2095         // Insert mapping in the database
2096         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2097         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2098         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
2099         etlr.setMaskLength((short) mask1);
2100         etlr.setRecordTtl(254);
2101         etlr.setAuthoritative(false);
2102         etlr.setAction(Action.NoAction);
2103         LocatorRecordBuilder record = new LocatorRecordBuilder();
2104         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2105         record.setRouted(true);
2106         record.setRlocProbed(false);
2107         record.setLocalLocator(false);
2108         record.setPriority((short) 1);
2109         record.setWeight((short) 50);
2110         record.setMulticastPriority((short) 1);
2111         record.setMulticastWeight((short) 1);
2112         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2113         etlr.getLocatorRecord().add(record.build());
2114         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2115         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2116         lms.handleMapRegister(mapRegister.build());
2117
2118         // Get mapping using NB interface. No IID used
2119         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
2120                 address1.getIpv4Address().getIpv4Address().getValue(),
2121                 mask1,
2122                 address2.getIpv4Address().getIpv4Address().getValue(),
2123                 mask2);
2124         String reply = callURL("GET", null, "application/json", null, url);
2125         JSONTokener jt = new JSONTokener(reply);
2126         JSONObject json = new JSONObject(jt);
2127
2128         // With just one locator, locators is not a JSONArray
2129         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
2130         .getString("ipAddress");
2131
2132         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
2133
2134     }
2135
2136     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
2137         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
2138                 address.getAfi().shortValue(),
2139                 address.getIpv4Address().getValue(), mask);
2140         URL url = new URL(restUrl);
2141         return url;
2142     }
2143
2144     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
2145             throws MalformedURLException {
2146         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
2147                 "key", afi, srcAddress, srcMask,
2148                 dstAddress, dstMask);
2149         URL url = new URL(restUrl);
2150         return url;
2151     }
2152
2153     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
2154             throws MalformedURLException {
2155         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
2156                 "mapping", afi, srcAddress,
2157                 srcMask, dstAddress, dstMask);
2158         URL url = new URL(restUrl);
2159         return url;
2160     }
2161
2162     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
2163         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
2164                 iid, address.getAfi()
2165                 .shortValue(), address.getIpv4Address().getValue(), mask);
2166         URL url = new URL(restUrl);
2167         return url;
2168     }
2169
2170     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
2171         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
2172                 iid, address.getAfi()
2173                 .shortValue(), address.getIpv4Address().getValue(), mask);
2174         URL url = new URL(restUrl);
2175         return url;
2176     }
2177
2178     private URL createPutURL(String resource) throws MalformedURLException {
2179
2180         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
2181
2182         URL url = new URL(restUrl);
2183         return url;
2184     }
2185
2186     private String createAuthenticationString() {
2187         String authString = "admin:admin";
2188         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
2189         String authStringEnc = new String(authEncBytes);
2190         return authStringEnc;
2191     }
2192
2193     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
2194             JSONException {
2195         String authStringEnc = createAuthenticationString();
2196         connection = (HttpURLConnection) url.openConnection();
2197         connection.setRequestMethod(method);
2198         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
2199         if (content != null) {
2200             connection.setRequestProperty("Content-Type", content);
2201         }
2202         if (accept != null) {
2203             connection.setRequestProperty("Accept", accept);
2204         }
2205         if (body != null) {
2206             // now add the request body
2207             connection.setDoOutput(true);
2208             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
2209             wr.write(body);
2210             wr.flush();
2211         }
2212         connection.connect();
2213
2214         // getting the result, first check response code
2215         Integer httpResponseCode = connection.getResponseCode();
2216
2217         if (httpResponseCode > 299) {
2218             LOG.trace("HTTP Address: " + url);
2219             LOG.trace("HTTP Response Code: " + httpResponseCode);
2220             fail();
2221         }
2222
2223         InputStream is = connection.getInputStream();
2224         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
2225         StringBuilder sb = new StringBuilder();
2226         int cp;
2227         while ((cp = rd.read()) != -1) {
2228             sb.append((char) cp);
2229         }
2230         is.close();
2231         connection.disconnect();
2232         return (sb.toString());
2233     }
2234
2235     // timePeriod - in ms
2236     public void assertNoPacketReceived(int timePeriod) {
2237         try {
2238             receivePacket(timePeriod);
2239             // If didn't timeout then fail:
2240             fail();
2241         } catch (SocketTimeoutException ste) {
2242         }
2243     }
2244 */
2245     // ------------------------------- Mask Tests ---------------------------
2246
2247     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
2248         cleanUP();
2249         runPrefixTest(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/16"),
2250                 LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.2/32"),
2251                 LispAddressUtil.asIpv4PrefixBinaryEid("1.1.1.1/32"));
2252     }
2253
2254     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
2255         cleanUP();
2256         runPrefixTest(LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:6:7:8/64"),
2257                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:1:2:3/128"),
2258                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:1:2:3:1:2/128"));
2259     }
2260
2261     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
2262             throws SocketTimeoutException {
2263         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
2264         sleepForSeconds(1);
2265
2266         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2267         mapRegister.setWantMapNotify(true);
2268         mapRegister.setNonce((long) 8);
2269         mapRegister.setWantMapNotify(true);
2270         mapRegister.setKeyId((short) 0);
2271         mapRegister.setAuthenticationData(new byte[0]);
2272         mapRegister.setNonce((long) 8);
2273         mapRegister.setProxyMapReply(false);
2274         MappingRecordBuilder etlr = new MappingRecordBuilder();
2275         etlr.setRecordTtl(254);
2276         etlr.setAction(Action.NoAction);
2277         etlr.setAuthoritative(false);
2278         etlr.setMapVersion((short) 0);
2279         etlr.setEid(registerEID);
2280         etlr.setRecordTtl(254);
2281         LocatorRecordBuilder record = new LocatorRecordBuilder();
2282         record.setLocatorId("4.3.2.1");
2283         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2284         record.setLocalLocator(false);
2285         record.setRlocProbed(false);
2286         record.setRouted(true);
2287         record.setMulticastPriority(Uint8.valueOf(0));
2288         record.setMulticastWeight(Uint8.valueOf(0));
2289         record.setPriority(Uint8.valueOf(0));
2290         record.setWeight(Uint8.valueOf(0));
2291         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2292         etlr.getLocatorRecord().add(record.build());
2293         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2294         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder()
2295                 .setMappingRecordItemId(LispAddressStringifier.getString(registerEID))
2296                 .setMappingRecord(etlr.build()).build());
2297         sendMapRegister(mapRegister.build());
2298         MapNotify mapNotify = receiveMapNotify();
2299         assertEquals(8, mapNotify.getNonce().longValue());
2300         sleepForSeconds(1);
2301         MapRequestBuilder mapRequest = new MapRequestBuilder();
2302         mapRequest.setNonce((long) 4);
2303         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
2304         mapRequest.setEidItem(new ArrayList<EidItem>());
2305         mapRequest.setAuthoritative(false);
2306         mapRequest.setMapDataPresent(false);
2307         mapRequest.setPitr(false);
2308         mapRequest.setProbe(false);
2309         mapRequest.setSmr(false);
2310         mapRequest.setSmrInvoked(false);
2311         mapRequest.getEidItem().add(new EidItemBuilder()
2312                 .setEidItemId(LispAddressStringifier.getString(matchedAddress))
2313                 .setEid(matchedAddress).build());
2314         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
2315         mapRequest.getItrRloc().add(new ItrRlocBuilder()
2316                 .setItrRlocId(ourAddress)
2317                 .setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2318         sendMapRequest(mapRequest.build());
2319         MapReply mapReply = receiveMapReply();
2320         assertEquals(4, mapReply.getNonce().longValue());
2321         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
2322                 .get(0).getRloc());
2323         mapRequest.setEidItem(new ArrayList<EidItem>());
2324         mapRequest.getEidItem().add(new EidItemBuilder()
2325                 .setEidItemId(LispAddressStringifier.getString(unMatchedAddress))
2326                 .setEid(unMatchedAddress).build());
2327         sendMapRequest(mapRequest.build());
2328         mapReply = receiveMapReply();
2329         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2330     }
2331 /*
2332     // This registers an IP with a MapRegister, then adds a password via the
2333     // northbound REST API
2334     // and checks that the password works
2335     public void testPasswordExactMatch() throws Exception {
2336         cleanUP();
2337         String ipString = "10.0.0.1";
2338         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
2339         int mask = 32;
2340         String pass = "pass";
2341
2342         URL url = createPutURL("key");
2343
2344         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
2345
2346         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
2347         LOG.trace("Address: " + address);
2348
2349         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
2350                 (byte) 31, (byte) 249, (byte) 87,
2351                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
2352                 (byte) 196, (byte) 62 };
2353
2354         byte[] zeros = new byte[20];
2355
2356         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
2357
2358         // build a MapRegister
2359         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2360         mapRegister.setWantMapNotify(true);
2361         mapRegister.setNonce((long) 8);
2362         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2363         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
2364         etlr.setMaskLength((short) mask);
2365         etlr.setRecordTtl(254);
2366         LocatorRecordBuilder record = new LocatorRecordBuilder();
2367         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2368         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2369         etlr.getLocatorRecord().add(record.build());
2370         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2371         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2372
2373         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
2374         mapRegister.setAuthenticationData(zeros);
2375
2376         sendMapRegister(mapRegister.build());
2377         assertNoPacketReceived(3000);
2378
2379         mapRegister.setAuthenticationData(expectedSha);
2380
2381         sendMapRegister(mapRegister.build());
2382
2383         assertMapNotifyReceived();
2384     }
2385
2386     public void testPasswordMaskMatch() throws Exception {
2387         cleanUP();
2388         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
2389         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
2390         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
2391
2392         int mask = 32;
2393         String pass = "pass";
2394
2395         URL url = createPutURL("key");
2396         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
2397
2398         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
2399         // build a MapRegister
2400         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2401
2402         mapRegister.setWantMapNotify(true);
2403         mapRegister.setNonce((long) 8);
2404         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2405         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
2406         etlr.setMaskLength((short) mask);
2407         etlr.setRecordTtl(254);
2408         LocatorRecordBuilder record = new LocatorRecordBuilder();
2409         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2410         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2411         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2412         etlr.getLocatorRecord().add(record.build());
2413         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2414         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2415
2416         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
2417         mapRegister
2418                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
2419                 -67, -113, 104, -110, -71 });
2420
2421         sendMapRegister(mapRegister.build());
2422
2423         assertMapNotifyReceived();
2424
2425         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
2426         mapRegister
2427                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
2428                 -71, -14, -99, 67, -23, -73 });
2429
2430         sendMapRegister(mapRegister.build());
2431         assertNoPacketReceived(3000);
2432     }
2433 */
2434     // takes an address, packs it in a MapRegister and sends it
2435     private void registerAddress(Eid eid) throws SocketTimeoutException {
2436         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2437         sleepForSeconds(1);
2438         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2439         sendMapRegister(mapRegister);
2440         MapNotify mapNotify = receiveMapNotify();
2441         assertEquals(8, mapNotify.getNonce().longValue());
2442     }
2443
2444     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
2445         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2446         mapRequestBuilder.setNonce((long) 4);
2447         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2448         mapRequestBuilder.getEidItem().add(new EidItemBuilder()
2449                 .setEidItemId(LispAddressStringifier.getString(eid))
2450                 .setEid(eid).build());
2451         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2452         if (srcEid != null) {
2453             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
2454         } else {
2455             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
2456                     .build());
2457         }
2458         mapRequestBuilder.getItrRloc().add(
2459                 new ItrRlocBuilder()
2460                         .setItrRlocId(ourAddress)
2461                         .setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2462         mapRequestBuilder.setAuthoritative(false);
2463         mapRequestBuilder.setMapDataPresent(false);
2464         mapRequestBuilder.setPitr(false);
2465         mapRequestBuilder.setProbe(false);
2466         mapRequestBuilder.setSmr(false);
2467         mapRequestBuilder.setSmrInvoked(false);
2468         sendMapRequest(mapRequestBuilder.build());
2469         return receiveMapReply();
2470     }
2471
2472     // takes an address, packs it in a MapRegister, sends it, returns the
2473     // MapReply
2474     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
2475         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2476         sleepForSeconds(1);
2477         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2478         LOG.trace("Sending Map-Register via socket: {}", mapRegister);
2479         sendMapRegister(mapRegister);
2480         MapNotify mapNotify = receiveMapNotify();
2481         LOG.trace("Received Map-Notify via socket: {}", mapNotify);
2482         assertEquals(8, mapNotify.getNonce().longValue());
2483         // wait for the notifications to propagate
2484         sleepForSeconds(1);
2485         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2486         sendMapRequest(mapRequest);
2487         return receiveMapReply();
2488     }
2489
2490     // ------------------------------- LCAF Tests ---------------------------
2491
2492     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
2493         cleanUP();
2494         String ipPrefix = "10.20.30.200/32";
2495         String macString = "01:02:03:04:05:06";
2496
2497         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
2498         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2499                 .ietf.inet.types.rev130715.Ipv4Prefix(ipPrefix))));
2500         builder.setDest(new SimpleAddress(new MacAddress(macString)));
2501
2502         EidBuilder eb = new EidBuilder();
2503         eb.setAddressType(SourceDestKeyLcaf.class);
2504         eb.setVirtualNetworkId(null);
2505         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2506                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
2507
2508         MapReply reply = registerAddressAndQuery(eb.build());
2509
2510         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2511         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
2512         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
2513
2514         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
2515         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
2516
2517         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
2518         assertNotNull(receivedAddr2.getMacAddress());
2519
2520         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
2521         MacAddress receivedMAC = receivedAddr2.getMacAddress();
2522
2523         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
2524         assertEquals(macString, receivedMAC.getValue());
2525     }
2526
2527     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
2528         cleanUP();
2529         String ipString1 = "10.10.10.0";
2530         String ipString2 = "20.20.20.0";
2531         String ipPrefix1 = ipString1 + "/24";
2532         String ipPrefix2 = ipString2 + "/24";
2533
2534         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
2535         registerAddress(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2));
2536         registerAddress(srcDst);
2537
2538         // exact match
2539         MapReply reply = queryForAddress(srcDst, null);
2540
2541         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2542         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
2543         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
2544
2545         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
2546         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
2547
2548         assertNotNull(receivedAddr1.getIpv4Prefix());
2549         assertNotNull(receivedAddr2.getIpv4Prefix());
2550
2551         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
2552         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
2553
2554         // srcEid/dstEid match
2555         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "10.10.10.1");
2556         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2557         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
2558
2559         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
2560
2561         // dstEid match only
2562         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "1.2.3.4");
2563         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2564         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
2565
2566         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
2567     }
2568
2569     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
2570         cleanUP();
2571         String ipString = "10.20.30.200";
2572         String macString = "01:02:03:04:05:06";
2573         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
2574         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
2575         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
2576
2577         MapReply reply = registerAddressAndQuery(kv);
2578
2579         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2580         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
2581         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
2582
2583         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
2584         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
2585
2586         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
2587         assertNotNull(receivedAddr2.getMacAddress());
2588
2589         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
2590         MacAddress receivedMAC = receivedAddr2.getMacAddress();
2591
2592         assertEquals(ipString, receivedIP.getValue());
2593         assertEquals(macString, receivedMAC.getValue());
2594     }
2595
2596     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
2597         cleanUP();
2598         String macString = "01:02:03:04:05:06";
2599         String ipString = "10.20.255.30";
2600         AfiListBuilder listbuilder = new AfiListBuilder();
2601         listbuilder.setAddressList(ImmutableSet.of(
2602                 new SimpleAddress(new IpAddress(new Ipv4Address(ipString))),
2603                 new SimpleAddress(new MacAddress(macString))));
2604
2605         EidBuilder eb = new EidBuilder();
2606         eb.setAddressType(AfiListLcaf.class);
2607         eb.setVirtualNetworkId(null);
2608         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2609                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
2610
2611         MapReply reply = registerAddressAndQuery(eb.build());
2612
2613         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2614
2615         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
2616
2617         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
2618         Iterator<SimpleAddress> addrList = listAddrFromNetwork.getAfiList().getAddressList().iterator();
2619         SimpleAddress receivedAddr1 = addrList.next();
2620         SimpleAddress receivedAddr2 = addrList.next();
2621
2622         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
2623         assertNotNull(receivedAddr2.getMacAddress());
2624
2625         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
2626         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
2627     }
2628
2629     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
2630         cleanUP();
2631         String ipString = "10.20.255.30";
2632         int instanceId = 6;
2633
2634         EidBuilder eb = new EidBuilder();
2635         eb.setAddressType(Ipv4PrefixAfi.class);
2636         eb.setVirtualNetworkId(new InstanceIdType(Uint32.valueOf(instanceId)));
2637         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
2638                 .yang.ietf.inet.types.rev130715.Ipv4Prefix(ipString)).build());
2639
2640         MapReply reply = registerAddressAndQuery(eb.build());
2641
2642         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2643         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
2644
2645         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
2646
2647         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
2648     }
2649
2650     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
2651         cleanUP();
2652         String macString = "01:02:03:04:05:06";
2653         String ipString = "10.20.255.30";
2654         HopBuilder hopBuilder = new HopBuilder();
2655         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2656         hopBuilder.setLrsBits(new LrsBits(true, false, true));
2657         Hop hop1 = hopBuilder.build();
2658         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
2659         hopBuilder.setLrsBits(new LrsBits(false, true, false));
2660         Hop hop2 = hopBuilder.build();
2661         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
2662         elpBuilder.setHop(new ArrayList<Hop>());
2663         elpBuilder.getHop().add(hop1);
2664         elpBuilder.getHop().add(hop2);
2665
2666         EidBuilder eb = new EidBuilder();
2667         eb.setAddressType(ExplicitLocatorPathLcaf.class);
2668         eb.setVirtualNetworkId(null);
2669         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2670                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
2671
2672         MapReply reply = registerAddressAndQuery(eb.build());
2673
2674         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
2675                 .getAddressType());
2676
2677         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
2678                 .getMappingRecord().getEid().getAddress();
2679
2680         Hop receivedHop1 = receivedAddress.getExplicitLocatorPath().getHop().get(0);
2681         Hop receivedHop2 = receivedAddress.getExplicitLocatorPath().getHop().get(1);
2682
2683         assertEquals(true, receivedHop1.getLrsBits().getLookup());
2684         assertEquals(false, receivedHop1.getLrsBits().getRlocProbe());
2685         assertEquals(true, receivedHop1.getLrsBits().getStrict());
2686
2687         assertEquals(false, receivedHop2.getLrsBits().getLookup());
2688         assertEquals(true, receivedHop2.getLrsBits().getRlocProbe());
2689         assertEquals(false, receivedHop2.getLrsBits().getStrict());
2690
2691         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
2692         assertNotNull(receivedHop2.getAddress().getMacAddress());
2693
2694         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
2695         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
2696     }
2697
2698     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
2699         cleanUP();
2700         String ipString = "1.2.3.4";
2701         final Uint8 protocol = Uint8.ONE;
2702         int ipTOs = 2;
2703         final Uint16 localPortLow = Uint16.valueOf(3);
2704         final Uint16 localPortHigh = Uint16.valueOf(4);
2705         final Uint16 remotePortLow = Uint16.valueOf(4);
2706         final Uint16 remotePortHigh = Uint16.valueOf(5);
2707
2708         ApplicationDataBuilder builder = new ApplicationDataBuilder();
2709         builder.setIpTos(ipTOs);
2710         builder.setProtocol(protocol);
2711         builder.setLocalPortLow(new PortNumber(localPortLow));
2712         builder.setLocalPortHigh(new PortNumber(localPortHigh));
2713         builder.setRemotePortLow(new PortNumber(remotePortLow));
2714         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
2715         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2716
2717         EidBuilder eb = new EidBuilder();
2718         eb.setAddressType(ApplicationDataLcaf.class);
2719         eb.setVirtualNetworkId(null);
2720         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2721                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
2722         Eid addressToSend = eb.build();
2723
2724         MapReply reply = registerAddressAndQuery(addressToSend);
2725
2726         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2727
2728         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
2729
2730         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
2731         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol());
2732         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
2733         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue());
2734         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue());
2735         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue());
2736         assertEquals(remotePortHigh,
2737                 receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue());
2738
2739         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
2740         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
2741     }
2742
2743     // ------------------- TimeOut Tests -----------
2744
2745     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
2746         cleanUP();
2747         ConfigIni.getInstance().setSmrRetryCount(0);
2748         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2749         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2750         sleepForSeconds(1);
2751
2752         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2753         sendMapRequest(mapRequest);
2754         MapReply mapReply = receiveMapReply();
2755         assertEquals(4, mapReply.getNonce().longValue());
2756         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2757
2758         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2759         sendMapRegister(mapRegister);
2760         MapNotify mapNotify = receiveMapNotify();
2761         assertEquals(8, mapNotify.getNonce().longValue());
2762         sleepForSeconds(1);
2763
2764         sendMapRequest(mapRequest);
2765         mapReply = receiveMapReply();
2766         assertEquals(4, mapReply.getNonce().longValue());
2767         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
2768                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
2769
2770         causeEntryToBeCleaned();
2771         sendMapRequest(mapRequest);
2772         mapReply = receiveMapReply();
2773         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2774     }
2775
2776     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
2777         cleanUP();
2778         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2779         MapRequest mapRequest = createMapRequest(eid);
2780
2781         testTTLBeforeRegister(mapRequest);
2782
2783         registerForTTL(eid);
2784
2785         testTTLAfterRegister(mapRequest);
2786
2787         causeEntryToBeCleaned();
2788         testTTLAfterClean(mapRequest);
2789
2790         //northboundAddKey();
2791         //testTTLAfterAutherize(mapRequest);
2792
2793     }
2794
2795     private void timedOutMappingRecord() {
2796         cleanUP();
2797         mapService.setMappingMerge(true);
2798         // mapping expires after 1 second
2799         ConfigIni.getInstance().setRegistrationValiditySb(1000L);
2800
2801         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32", new InstanceIdType(Uint32.TEN));
2802         final MappingRecord mappingRecord = MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(eid)
2803                 .setRecordTtl(1000).build();
2804
2805         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2806         mapService.addMapping(MappingOrigin.Southbound, eid, MappingServiceIntegrationTestUtil.DEFAULT_SITE_ID,
2807                 new MappingData(mappingRecord, System.currentTimeMillis()));
2808         sleepForSeconds(2);
2809
2810         MappingRecord resultRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, eid);
2811         assertNull(resultRecord);
2812         ConfigIni.getInstance().setRegistrationValiditySb(ConfigIni.getInstance().getDefaultRegistrationValiditySb());
2813     }
2814
2815     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
2816         MapReply mapReply;
2817         sendMapRequest(mapRequest);
2818         mapReply = receiveMapReply();
2819         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2820     }
2821
2822     private void causeEntryToBeCleaned() {
2823         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
2824         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
2825         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
2826         mapService.cleanCachedMappings();
2827     }
2828
2829     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
2830         MapReply mapReply;
2831         sendMapRequest(mapRequest);
2832         mapReply = receiveMapReply();
2833         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2834                 .getLocatorRecord().get(0).getRloc());
2835         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
2836     }
2837
2838     private void registerForTTL(Eid eid) throws SocketTimeoutException {
2839         MapRegister mapRegister = createMapRegister(eid);
2840         sendMapRegister(mapRegister);
2841         assertMapNotifyReceived();
2842     }
2843
2844     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
2845         MapReply mapReply;
2846         sendMapRequest(mapRequest);
2847         mapReply = receiveMapReply();
2848         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2849     }
2850 /*
2851     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
2852         MapReply mapReply;
2853         sendMapRequest(mapRequest);
2854         mapReply = receiveMapReply();
2855         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
2856     }
2857 */
2858     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
2859         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
2860         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
2861     }
2862
2863     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
2864         return MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid, rloc).build();
2865     }
2866
2867     private MapRegister createMapRegister(Eid eid) {
2868         return MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2869     }
2870
2871     private MapRequest createMapRequest(Eid eid) {
2872         return MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2873     }
2874
2875     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
2876         cleanUP();
2877         String rloc = "127.0.0.3";
2878         int port = LispMessage.PORT_NUM;
2879         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
2880         sendProxyMapRequest(rloc, port, ipRloc);
2881
2882     }
2883
2884     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
2885         cleanUP();
2886         String rloc = "127.0.0.3";
2887         int port = 4350;
2888
2889         RlocBuilder rb = new RlocBuilder();
2890         rb.setAddressType(ApplicationDataLcaf.class);
2891         rb.setVirtualNetworkId(null);
2892         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2893                 .lisp.address.address.ApplicationDataBuilder()
2894                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2895                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(Uint16.valueOf(port))).build()).build());
2896         Rloc adLcaf = rb.build();
2897
2898         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
2899         sendProxyMapRequest(rloc, port, adLcaf);
2900
2901     }
2902
2903     private class XtrRequestMappingListener implements OdlLispProtoListener {
2904
2905         @Override
2906         public void onGotMapReply(GotMapReply notification) {
2907         }
2908
2909         @Override
2910         public void onAddMapping(AddMapping notification) {
2911         }
2912
2913         @Override
2914         public void onXtrReplyMapping(XtrReplyMapping notification) {
2915         }
2916
2917         @Override
2918         public void onRequestMapping(RequestMapping notification) {
2919         }
2920
2921         @Override
2922         public void onGotMapNotify(GotMapNotify notification) {
2923         }
2924
2925         @Override
2926         public void onXtrRequestMapping(XtrRequestMapping notification) {
2927         }
2928
2929         @Override
2930         public void onMappingKeepAlive(MappingKeepAlive notification) {
2931         }
2932
2933     }
2934
2935     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
2936         cleanUP();
2937         configLispPlugin.shouldListenOnXtrPort(true);
2938         notificationCalled = false;
2939         final String eid = "10.10.10.10/32";
2940         String rloc = "127.0.0.3";
2941         int port = LispMessage.XTR_PORT_NUM;
2942
2943         RlocBuilder rb = new RlocBuilder();
2944         rb.setAddressType(ApplicationDataLcaf.class);
2945         rb.setVirtualNetworkId(null);
2946         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2947                 .lisp.address.address.ApplicationDataBuilder()
2948                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2949                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(Uint16.valueOf(port))).build()).build());
2950         Rloc adLcaf = rb.build();
2951
2952         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2953         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
2954                 new XtrRequestMappingListener() {
2955
2956             @Override
2957             public void onXtrRequestMapping(XtrRequestMapping notification) {
2958                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
2959                         .getIpv4Prefix().getValue(), eid);
2960                 notificationCalled = true;
2961                 LOG.warn("notification arrived");
2962             }
2963         });
2964         sendMapRequest(mapRequest, port);
2965         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
2966             if (notificationCalled) {
2967                 return;
2968             } else {
2969                 LOG.warn("notification hasn't arrived, sleeping...");
2970                 Thread.sleep(500);
2971             }
2972         }
2973
2974         fail("Notification hasn't arrived");
2975
2976     }
2977
2978     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
2979             SocketException {
2980         String eid = "10.1.0.1/32";
2981         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2982         sendMapRequest(mapRequest);
2983         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
2984         MapRequest receivedMapRequest = MappingServiceIntegrationTestUtil.receiveMapRequest(
2985                 nonProxySocket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
2986         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
2987         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
2988         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
2989         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
2990         nonProxySocket.close();
2991     }
2992
2993     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
2994         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2995         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
2996                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
2997         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
2998         sendMapRegister(mr);
2999         assertMapNotifyReceived();
3000         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
3001         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
3002         builder.setPitr(true);
3003         mapRequest = builder.build();
3004         return mapRequest;
3005     }
3006
3007     private void sendMapRequest(MapRequest mapRequest) {
3008         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
3009     }
3010
3011     private void sendMapRequest(MapRequest mapRequest, int port) {
3012         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
3013     }
3014
3015     private void sendMapRegister(MapRegister mapRegister) {
3016         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
3017     }
3018
3019     private void sendPacket(byte[] bytesToSend) {
3020         sendPacket(bytesToSend, LispMessage.PORT_NUM);
3021     }
3022
3023     private void sendPacket(byte[] bytesToSend, int port) {
3024         MappingServiceIntegrationTestUtil.sendPacket(socket, bytesToSend, port);
3025     }
3026
3027     private ByteBuffer receivePacket() throws SocketTimeoutException {
3028         return MappingServiceIntegrationTestUtil.receivePacket(socket);    }
3029
3030     private ByteBuffer receivePacket(int timeout) throws SocketTimeoutException {
3031         return MappingServiceIntegrationTestUtil.receivePacket(socket, timeout);
3032     }
3033
3034     private void assertMapNotifyReceived() throws SocketTimeoutException {
3035         MappingServiceIntegrationTestUtil.receiveMapNotify(
3036                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3037     }
3038
3039     private MapRequest receiveMapRequest() throws SocketTimeoutException {
3040         return MappingServiceIntegrationTestUtil.receiveMapRequest(
3041                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3042     }
3043
3044     private MapReply receiveMapReply() throws SocketTimeoutException {
3045         return MappingServiceIntegrationTestUtil.receiveMapReply(
3046                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3047     }
3048
3049     private MapNotify receiveMapNotify() throws SocketTimeoutException {
3050         return MappingServiceIntegrationTestUtil.receiveMapNotify(
3051                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3052     }
3053
3054     private void sleepForSeconds(int seconds) {
3055         try {
3056             Thread.sleep(seconds*1000);
3057         } catch (InterruptedException e) {
3058             LOG.warn("Interrupted while sleeping", e);
3059         }
3060     }
3061
3062     private void sleepForMilliseconds(long milliseconds) {
3063         try {
3064             Thread.sleep(milliseconds);
3065         } catch (InterruptedException e) {
3066             LOG.warn("Interrupted while sleeping", e);
3067         }
3068     }
3069
3070     private byte[] extractWSUdpByteArray(String wiresharkHex) {
3071         final int HEADER_LEN = 42;
3072         byte[] res = new byte[1000];
3073         String[] split = wiresharkHex.split(" ");
3074         int counter = 0;
3075         for (String cur : split) {
3076             cur = cur.trim();
3077             if (cur.length() == 2) {
3078                 ++counter;
3079                 if (counter > HEADER_LEN) {
3080                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
3081                 }
3082
3083             }
3084         }
3085         return Arrays.copyOf(res, counter - HEADER_LEN);
3086     }
3087
3088     private String stateToString(int state) {
3089         switch (state) {
3090         case Bundle.ACTIVE:
3091             return "ACTIVE";
3092         case Bundle.INSTALLED:
3093             return "INSTALLED";
3094         case Bundle.RESOLVED:
3095             return "RESOLVED";
3096         case Bundle.UNINSTALLED:
3097             return "UNINSTALLED";
3098         default:
3099             return "Not CONVERTED";
3100         }
3101     }
3102
3103     private void areWeReady() throws InvalidSyntaxException {
3104         sleepForSeconds(5);
3105
3106         assertNotNull(bc);
3107         boolean debugit = false;
3108         Bundle b[] = bc.getBundles();
3109         for (Bundle element : b) {
3110             int state = element.getState();
3111             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
3112                     + element.getVersion() + ", state:" + stateToString(state));
3113             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
3114                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
3115
3116                 // try {
3117                 // String host = element.getHeaders().get("FRAGMENT-HOST");
3118                 // if (host != null) {
3119                 // LOG.warn("Bundle " + element.getSymbolicName() +
3120                 // " is a fragment which is part of: " + host);
3121                 // LOG.warn("Required imports are: " +
3122                 // element.getHeaders().get("IMPORT-PACKAGE"));
3123                 // } else {
3124                 // element.start();
3125                 // }
3126                 // } catch (BundleException e) {
3127                 // LOG.error("BundleException:", e);
3128                 // fail();
3129                 // }
3130
3131                 debugit = true;
3132
3133             }
3134         }
3135         if (debugit) {
3136             LOG.warn(("Do some debugging because some bundle is unresolved"));
3137         }
3138         // assertNotNull(broker);
3139
3140         configLispPlugin.setLispAddress(lispBindAddress);
3141
3142         // Uncomment this code to Know which services were actually loaded to
3143         // BundleContext
3144
3145         /*
3146         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
3147             LOG.info(sr.getBundle().getSymbolicName());
3148             LOG.info(sr.toString());
3149         }
3150         */
3151
3152         sleepForSeconds(1);
3153     }
3154
3155     private void cleanUP() {
3156         LOG.debug("\n\n\nCleaning up...\n\n");
3157         mapService.cleanCachedMappings();
3158         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
3159         configLispPlugin.shouldListenOnXtrPort(false);
3160         MappingServiceIntegrationTestUtil.drainSocket(socket);
3161         LOG.debug("\n\n\n... finished cleaning up!\n\n");
3162     }
3163
3164     private void restartSocket() {
3165         after();
3166         socket = MappingServiceIntegrationTestUtil.initSocket(LispMessage.PORT_NUM);
3167         MappingServiceIntegrationTestUtil.drainSocket(socket);
3168     }
3169
3170 }