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