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