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