Make part of the Subscribers object modeled
[lispflowmapping.git] / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.java
1 /*
2  * Copyright (c) 2014 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_RLOC_10;
21 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_SB;
22 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_100_1_SB;
23 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_50_2_SB;
24 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D4;
25 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D5;
26 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_DELETE_SB;
27 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_100_1_SB;
28 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_50_2_SB;
29 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_E_SB;
30 import static org.ops4j.pax.exam.CoreOptions.composite;
31 import static org.ops4j.pax.exam.CoreOptions.maven;
32 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
33
34 import com.google.common.collect.Lists;
35 import com.google.common.collect.Sets;
36 import com.google.common.net.InetAddresses;
37 import java.io.IOException;
38 import java.net.DatagramPacket;
39 import java.net.DatagramSocket;
40 import java.net.InetAddress;
41 import java.net.InetSocketAddress;
42 import java.net.SocketException;
43 import java.net.SocketTimeoutException;
44 import java.net.UnknownHostException;
45 import java.nio.ByteBuffer;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.List;
49 import java.util.Set;
50 import javax.inject.Inject;
51 import org.junit.After;
52 import org.junit.Assert;
53 import org.junit.Before;
54 import org.junit.Test;
55 import org.junit.runner.RunWith;
56 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
57 import org.opendaylight.lispflowmapping.config.ConfigIni;
58 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
59 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
60 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
61 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
62 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
63 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
64 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
65 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
66 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
67 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
68 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
69 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
70 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
71 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
72 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
98 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;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop.LrsBits;
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.HopBuilder;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4BinaryBuilder;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkeyBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
143 import org.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     /**
162      * Defines how many attempt to create instance of DatagramSocket will be done before giving up.
163      */
164     private static final int NUM_OF_ATTEMPTS_TO_CREATE_SOCKET = 2;
165
166     private byte[] mapRequestPacket;
167     private byte[] mapRegisterPacketWithNotify;
168     private byte[] mapRegisterPacketWithoutNotify;
169     String lispBindAddress = "127.0.0.1";
170     static final String ourAddress = "127.0.0.2";
171     private Rloc locatorEid;
172     private DatagramSocket socket;
173     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
174
175     public static final String ODL = "org.opendaylight.controller";
176     public static final String YANG = "org.opendaylight.yangtools";
177     private static final int MULTI_SITE_SLEEP_TIME = 1;
178     private static final int MAX_NOTIFICATION_RETRYS = 20;
179     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(0).build();
180
181     // This is temporary, since the properties in the pom file are not picked up
182     @Override
183     public String getKarafDistro() {
184         return maven()
185                 .groupId("org.opendaylight.lispflowmapping")
186                 .artifactId("distribution-karaf")
187                 .versionAsInProject()
188                 .type("zip")
189                 .getURL();
190     }
191
192     @Override
193     public MavenUrlReference getFeatureRepo() {
194         return maven()
195                 .groupId("org.opendaylight.lispflowmapping")
196                 .artifactId("features-lispflowmapping")
197                 .classifier("features")
198                 .type("xml")
199                 .versionAsInProject();
200     }
201
202     @Override
203     public String getFeatureName() {
204         return "odl-lispflowmapping-msmr";
205     }
206
207     @Override
208     public Option getLoggingOption() {
209         Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
210                 "log4j.logger.org.opendaylight.lispflowmapping",
211                 LogLevel.DEBUG.name());
212         option = composite(option, super.getLoggingOption());
213         return option;
214     }
215
216     @Test
217     public void testLispFlowMappingFeatureLoad() {
218         Assert.assertTrue(true);
219     }
220
221     @After
222     public void after() {
223         if (socket != null) {
224             socket.close();
225         }
226         // reset mapping record validity to default value
227         ConfigIni.getInstance().setRegistrationValiditySb(200000L);
228     }
229
230     @Before
231     public void before() throws Exception {
232         areWeReady();
233         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
234         mapService.setMappingMerge(false);
235         ConfigIni.getInstance().setSmrRetryCount(1);
236
237         locatorEid = LispAddressUtil.asIpv4Rloc("4.3.2.1");
238         socket = initSocket(socket, LispMessage.PORT_NUM);
239
240         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
241         // LISP(Type = 8 - Encapsulated)
242         // IP: 192.168.136.10 -> 153.16.254.1
243         // UDP: 56756
244         // LISP(Type = 1 Map-Request
245         // Record Count: 1
246         // ITR-RLOC count: 0
247         // Source EID AFI: 1
248         // Source EID 1.2.3.4
249         // Nonce: 0x3d8d2acd39c8d608
250         // ITR-RLOC AFI=1 Address=192.168.136.10
251         // Record 1: 153.16.254.1/32
252         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
253                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
254                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
255                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
256                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
257                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
258                 + "0060   00 01 99 10 fe 01"));
259
260         // IP: 192.168.136.10 -> 128.223.156.35
261         // UDP: 49289 -> 4342
262         // LISP(Type = 3 Map-Register, P=1, M=1
263         // Record Counter: 1
264         // Nonce: 0
265         // Key ID: 0x0001
266         // AuthDataLength: 20 Data:
267         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
268         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
269         // No-Action
270         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
271         // Priority/Weight: 1/100, Multicast Priority/Weight:
272         // 255/0
273         //
274
275         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String(
276                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
277                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
278                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
279                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
280                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
281                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
282                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
283
284         // IP: 192.168.136.10 -> 128.223.156.35
285         // UDP: 49289 -> 4342
286         // LISP(Type = 3 Map-Register, P=1, M=1
287         // Record Counter: 1
288         // Nonce: 7
289         // Key ID: 0x0000 NO AUTHENTICATION!!
290         // AuthDataLength: 00 Data:
291         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
292         // No-Action
293         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
294         // Priority/Weight: 1/100, Multicast Priority/Weight:
295         // 255/0
296         //
297
298         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String(
299                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
300                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
301                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
302                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
303                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
304                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
305                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
306
307         // IP: 192.168.136.10 -> 128.223.156.35
308         // UDP: 49289 -> 4342
309         // LISP(Type = 3 Map-Register, P=1, M=1
310         // Record Counter: 1
311         // Nonce: 7
312         // Key ID: 0x0000 NO AUTHENTICATION!!
313         // AuthDataLength: 00 Data:
314         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
315         // No-Action
316         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
317         // Priority/Weight: 1/100, Multicast Priority/Weight:
318         // 255/0
319         //
320
321         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String(
322                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
323                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
324                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
325                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
326                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
327                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
328                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
329     }
330
331     @Inject
332     private BundleContext bc;
333     //private HttpURLConnection connection;
334     protected static boolean notificationCalled;
335
336     @Inject @Filter(timeout=60000)
337     private IFlowMapping lms;
338
339     @Inject @Filter(timeout=60000)
340     private IMappingService mapService;
341
342     @Inject @Filter(timeout=10000)
343     private IConfigLispSouthboundPlugin configLispPlugin;
344
345     @Test
346     public void testSimpleUsage() throws Exception {
347         mapRequestSimple();
348         mapRegisterWithMapNotify();
349         mapRegisterWithMapNotifyAndMapRequest();
350         registerAndQuery__MAC();
351         mapRequestMapRegisterAndMapRequest();
352         mapRegisterWithAuthenticationWithoutConfiguringAKey();
353         mapRegisterWithoutMapNotify();
354     }
355
356     @Test
357     public void testLCAFs() throws Exception {
358         registerAndQuery__SrcDestLCAF();
359         registerAndQuery__SrcDestLCAFOverlap();
360         registerAndQuery__KeyValueLCAF();
361         //registerAndQuery__ListLCAF();
362         //registerAndQuery__ApplicationData();
363         //registerAndQuery__TrafficEngineering();
364         //registerAndQuery__SegmentLCAF();
365     }
366
367     @Test
368     public void testMask() throws Exception {
369         //testPasswordExactMatch();                     TODO commented because it needs NB
370         //testPasswordMaskMatch();                      TODO commented because it needs NB
371         eidPrefixLookupIPv4();
372         eidPrefixLookupIPv6();
373     }
374 /*
375     @Test
376     public void testNorthbound() throws Exception {
377         northboundAddKey();
378         northboundAddMapping();
379         northboundDeleteMapping();
380         northboundRetrieveKey();
381         northboundRetrieveMapping();
382         northboundRetrieveSourceDestKey();
383         northboundRetrieveSourceDestMapping();
384     }
385 */
386     @Test
387     public void testOverWriting() throws Exception {
388         //testMapRegisterDosntOverwritesOtherSubKeys(); TODO weird failure, needs debug
389
390         // TODO: remove, we don't support overwrite flag any longer and RLOCs are not saved as independent RLOC groups
391         // testMapRegisterOverwritesSameSubkey();
392         // testMapRegisterOverwritesNoSubkey();
393         // testMapRegisterDoesntOverwritesNoSubkey();
394     }
395
396     @Test
397     public void testTimeOuts() throws Exception {
398         timedOutMappingRecord();
399         mapRequestMapRegisterAndMapRequestTestTimeout();
400         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
401     }
402
403 //    @Test
404 //    public void testNonProxy() throws Throwable {
405 //        testSimpleNonProxy();
406 //        testNonProxyOtherPort();
407 //        testRecievingNonProxyOnXtrPort();
408 //    }
409
410     @Test
411     public void testSmr() throws Exception {
412         registerQueryRegisterWithSmr();
413         testRepeatedSmr();
414     }
415
416     @Test
417     public void testMultiSite() throws Exception {
418         testMultiSiteScenarioA();
419         testMultiSiteScenarioB();
420     }
421
422     @Test
423     public void testNegativePrefix_gapIntersection() throws UnknownHostException {
424         insertMappings();
425         testGapIntersection();
426
427         insertMappings();
428         testMultipleMappings();
429     }
430
431     private void testRepeatedSmr() throws SocketTimeoutException, UnknownHostException {
432         cleanUP();
433         long timeout = ConfigIni.getInstance().getSmrTimeout();
434         ConfigIni.getInstance().setSmrRetryCount(5);
435
436         final InstanceIdType iid = new InstanceIdType(1L);
437         final Eid eid1 = LispAddressUtil.asIpv4Eid("1.1.1.1", 1L);
438         final int expectedSmrs1 = 2;
439         final int expectedSmrs2 = 3;
440
441         /* set auth */
442         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
443         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
444
445         /* add subscribers */
446         final String subscriberSrcRloc1 = "127.0.0.3";
447         final String subscriberSrcRloc2 = "127.0.0.4";
448         final Set<Subscriber> subscriberSet1 = Sets.newHashSet(newSubscriber(eid1, subscriberSrcRloc1),
449                 newSubscriber(eid1, subscriberSrcRloc2));
450         mapService.addData(MappingOrigin.Southbound, eid1, SubKeys.SUBSCRIBERS, subscriberSet1);
451
452         final SocketReader reader1 = startSocketReader(subscriberSrcRloc1, 15000);
453         final SocketReader reader2 = startSocketReader(subscriberSrcRloc2, 15000);
454         sleepForSeconds(1);
455
456         /* add mapping */
457         final MappingRecord mapping1 = new MappingRecordBuilder()
458                 .setEid(eid1).setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
459         mapService.addMapping(MappingOrigin.Northbound, eid1, null, new MappingData(mapping1));
460
461         sleepForMilliseconds((timeout * expectedSmrs1) - (timeout / 2));
462         final List<MapRequest> requests1 = processSmrPackets(reader1, subscriberSrcRloc1, expectedSmrs1);
463         final MapReply mapReply1 = lms.handleMapRequest(
464                 new MapRequestBuilder(requests1.get(0))
465                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
466                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc1)).build()))
467                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
468                         .setSmrInvoked(true)
469                         .setSmr(false).build());
470
471         // sleep to get 1 extra smr request
472         sleepForMilliseconds(timeout * 1);
473         final List<MapRequest> requests2 = processSmrPackets(reader2, subscriberSrcRloc2, expectedSmrs2);
474         final MapReply mapReply2 = lms.handleMapRequest(
475                 new MapRequestBuilder(requests2.get(0))
476                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
477                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc2)).build()))
478                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
479                         .setSmrInvoked(true)
480                         .setSmr(false).build());
481
482         sleepForSeconds(3);
483         assertEquals(expectedSmrs1, requests1.size());
484         assertEquals(expectedSmrs2, requests2.size());
485         assertEquals((long) mapReply1.getNonce(), (long) requests1.get(0).getNonce());
486         assertEquals((long) mapReply2.getNonce(), (long) requests2.get(0).getNonce());
487         assertNextBufferEmpty(reader1);
488         assertNextBufferEmpty(reader2);
489
490         reader1.stopReading();
491         reader2.stopReading();
492     }
493
494     private SocketReader startSocketReader(String address, int timeout) {
495         DatagramSocket receivingSocket = null;
496
497         try {
498             receivingSocket = new DatagramSocket(new InetSocketAddress(address, LispMessage.PORT_NUM));
499         } catch (SocketException e) {
500             LOG.error("Can't initialize socket for {}", address, e);
501         }
502         return SocketReader.startReadingInStandaloneThread(receivingSocket, timeout);
503     }
504
505     private List<MapRequest> processSmrPackets(SocketReader reader, String address, int expectedSmrs) {
506         InetAddress inetAddress = null;
507         try {
508             inetAddress = InetAddress.getByName(address);
509         } catch (UnknownHostException e) {
510             LOG.error("Unknown address {}.", address, e);
511         }
512
513         final List<MapRequest> requests = Lists.newArrayList();
514         byte[][] buffers = reader.getBuffers(expectedSmrs);
515         for (byte[] buf : buffers) {
516             MapRequest request = MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(buf), inetAddress);
517             requests.add(request);
518         }
519         return requests;
520     }
521
522     private void assertNextBufferEmpty(SocketReader socketReader) {
523         assertTrue(isArrayEmpty(socketReader.getBuffers(1)[0]));
524     }
525
526     private boolean isArrayEmpty(byte[] byteArray) {
527         for (byte b : byteArray) {
528             if (b != 0) {
529                 return false;
530             }
531         }
532         return true;
533     }
534
535     private static Subscriber newSubscriber(Eid srcEid, String srcRlocIp) {
536         final byte[] addressBinary = InetAddresses.forString(srcRlocIp).getAddress();
537         final int timeout = 5;
538         final Rloc srcRloc = new RlocBuilder().setAddress(new Ipv4BinaryBuilder()
539                 .setIpv4Binary(new Ipv4AddressBinary(addressBinary)).build()).build();
540
541         return new Subscriber(srcRloc, srcEid, timeout);
542     }
543
544     private void testMultipleMappings() throws UnknownHostException {
545         final InstanceIdType iid = new InstanceIdType(1L);
546         final String prefix1 = "1.1.127.10/32"; // prefix from the intersection of NB and SB gaps
547         final String prefix2 = "1.1.200.255/32"; // prefix with existing mapping in NB
548         final String prefix3 = "1.3.255.255/32";
549
550         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
551                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid))
552                         .build(),
553                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid))
554                         .build(),
555                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid))
556                         .build()))
557                 .build();
558         final MapReply mapReply = lms.handleMapRequest(mapRequest);
559
560         // expected result
561         final String resultPrefix1 = "1.1.64.0";
562         final Address resultNegMapping1 = new Ipv4PrefixBinaryBuilder()
563                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix1).getAddress()))
564                 .setIpv4MaskLength((short) 18).build();
565
566         final String resultPrefix2 = "1.1.192.0";
567         final Address resultMapping2 = new Ipv4PrefixBinaryBuilder()
568                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix2).getAddress()))
569                 .setIpv4MaskLength((short) 18).build();
570
571         final String resultPrefix3 = "1.3.0.0";
572         final Address resultNegMapping3 = new Ipv4PrefixBinaryBuilder()
573                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix3).getAddress()))
574                 .setIpv4MaskLength((short) 16).build();
575
576         assertEquals(resultNegMapping1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
577                 .getAddress());
578         assertEquals(resultMapping2, mapReply.getMappingRecordItem().get(1).getMappingRecord().getEid()
579                 .getAddress());
580         assertEquals(resultNegMapping3, mapReply.getMappingRecordItem().get(2).getMappingRecord().getEid()
581                 .getAddress());
582     }
583
584     /**
585      * Tests a negative mapping from an intersection of gaps in northbound and southbound.
586      */
587     private void testGapIntersection() throws UnknownHostException {
588         final InstanceIdType iid = new InstanceIdType(1L);
589
590         // request an Eid from a gap between mappings
591         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
592                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid("1.1.127.10/32", iid))
593                         .build()))
594                 .build();
595         final MapReply mapReply = lms.handleMapRequest(mapRequest);
596
597         // expected negative mapping
598         final Address resultNegMapping = new Ipv4PrefixBinaryBuilder()
599                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName("1.1.64.0").getAddress()))
600                 .setIpv4MaskLength((short) 18).build();
601         assertEquals(resultNegMapping, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
602                 .getAddress());
603     }
604
605     private void insertMappings() {
606         cleanUP();
607         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
608
609         final InstanceIdType iid = new InstanceIdType(1L);
610         final String prefixNbLeft = "1.2.0.0/16";
611         final String prefixNbRight = "1.1.128.0/17";
612         final String prefixSbLeft = "1.1.32.0/19";
613         final String prefixSbRight = "1.0.0.0/8";
614
615         final MappingRecord mapRecordNbLeft = newMappingRecord(prefixNbLeft, iid);
616         final MappingRecord mapRecordNbRight = newMappingRecord(prefixNbRight, iid);
617         final MappingRecord mapRecordSbLeft = newMappingRecord(prefixSbLeft, iid);
618         final MappingRecord mapRecordSbRight = newMappingRecord(prefixSbRight, iid);
619
620         /* set auth */
621         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
622         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
623
624         mapService.addMapping(MappingOrigin.Northbound, mapRecordNbLeft.getEid(), null,
625                 new MappingData(mapRecordNbLeft));
626         mapService.addMapping(MappingOrigin.Northbound, mapRecordNbRight.getEid(), null,
627                 new MappingData(mapRecordNbRight));
628         mapService.addMapping(MappingOrigin.Southbound, mapRecordSbLeft.getEid(), null,
629                 new MappingData(mapRecordSbLeft, System.currentTimeMillis()));
630         mapService.addMapping(MappingOrigin.Southbound, mapRecordSbRight.getEid(), null,
631                 new MappingData(mapRecordSbRight, System.currentTimeMillis()));
632
633         restartSocket();
634         sleepForSeconds(2);
635     }
636
637     /**
638      * Creates a new MappingRecord object.
639      *
640      * @param prefix The Eid prefix
641      * @param iid VNI
642      * @return new MappingRecord object
643      */
644     private MappingRecord newMappingRecord(String prefix, InstanceIdType iid) {
645         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
646         return new MappingRecordBuilder()
647                 .setEid(prefixBinary)
648                 .setLocatorRecord(Lists.newArrayList(new LocatorRecordBuilder()
649                         .setRloc(LispAddressUtil.asIpv4Rloc("2.2.2.2")).setLocatorId("loc_id").build()))
650                 .setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
651     }
652
653     /**
654      * TEST SCENARIO A
655      */
656     public void testMultiSiteScenarioA() throws IOException {
657         cleanUP();
658         ConfigIni.getInstance().setSmrRetryCount(1);
659
660         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
661         multiSiteScenario.setCommonAuthentication();
662
663         restartSocket();
664         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
665
666         //TEST CASE 1
667         multiSiteScenario.storeSouthboundMappings(false, SITE_A, SITE_B, SITE_C, SITE_D4, SITE_D5);
668         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
669         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
670         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
671         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
672         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
673         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
674
675         //TEST CASE 2
676         //following action should trigger generatting of SMR messages:
677         // 1) 192.0.2.5/32
678         // 2) 192.0.1.1/32
679         multiSiteScenario.storeNorthMappingSrcDst(SITE_A, SITE_C);
680         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
681         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1));
682         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
683         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
684         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
685
686         //TEST CASE 3
687         // following action should trigger generatting of SMR messages:
688         // 1) 192.0.2.5/32
689         // 2) 192.0.1.1/32
690         // 3) 192.0.1.5/32
691         // 4) 192.0.4.5/32
692         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
693         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
694         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1), SITE_A
695                         .getHost(5),
696                 SITE_D4.getHost(5));
697         multiSiteScenario.assertPingWorks(SITE_D4, 5, SITE_C, 4);
698
699         //TEST CASE 4
700         // following action should trigger generatting of SMR messages:
701         // 1) 192.0.4.5/32
702         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C_RLOC_10);
703         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
704         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D4.getHost(5));
705         //way of testing ping - get RLOC for mapping src-dst and compare it with awaited value doesn't test
706         //that ping won't be successfull
707         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
708
709         //TEST CASE 5
710         // following action should trigger generatting of SMR messages:
711         // 1) 192.0.4.5/32
712         // 2) 192.0.2.5/32
713         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
714         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
715         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D4.getHost(5), SITE_B.getHost(5));
716         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
717
718         //TEST CASE 6
719         multiSiteScenario.assertPingFails(SITE_D5, 5, SITE_C, 3);
720
721         //TEST CASE 7
722         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A, SITE_C);
723         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
724         // following action should trigger generatting of SMR messages:
725         // 1) 192.0.4.5/32
726         // 2) 192.0.2.5/32
727         // 3) 192.0.5.5/32
728         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
729                 SITE_B.getHost(5));
730
731         // following action should trigger generatting of SMR messages:
732         // 1) 192.0.4.5/32
733         // 2) 192.0.2.5/32
734         // 3) 192.0.5.5/32
735         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
736         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
737         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
738                 SITE_B.getHost(5));
739
740         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
741         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
742         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
743
744         //TEST CASE 8
745         // following action should trigger generatting of SMR messages:
746         // 1) 192.0.4.5/32
747         // 2) 192.0.2.5/32
748         // 3) 192.0.5.5/32
749         // 4) 192.0.1.1/32
750         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B, SITE_C);
751         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
752         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
753                 SITE_B.getHost(5),
754                 SITE_A.getHost(1));
755         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
756         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
757         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
758
759         //TEST CASE 9
760         // following action should trigger generatting of SMR messages:
761         // 1) 192.0.4.5/32
762         // 2) 192.0.2.5/32
763         // 3) 192.0.5.5/32
764         // 4) 192.0.1.1/32
765         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
766         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
767         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
768                 SITE_B.getHost(5),
769                 SITE_A.getHost(1));
770         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
771         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
772         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
773
774         socketReader.stopReading();
775
776     }
777
778     /**
779      * TEST SCENARIO B
780      */
781     public void testMultiSiteScenarioB() throws IOException {
782         cleanUP();
783
784         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
785         multiSiteScenario.setCommonAuthentication();
786
787         restartSocket();
788         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
789
790         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
791         mapService.setMappingMerge(true);
792
793         //TEST CASE 1
794         multiSiteScenario.storeSouthboundMappings(true, SITE_A_SB, SITE_B_SB, SITE_C_WP_100_1_SB, SITE_D_WP_100_1_SB,
795                 SITE_E_SB);
796         multiSiteScenario.storeNorthMappingIpPrefix(SITE_A_SB);
797         multiSiteScenario.storeNorthMappingIpPrefix(SITE_B_SB);
798         multiSiteScenario.storeNorthMappingIpPrefix(SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
799         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
800         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
801         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
802
803         //TEST CASE 2
804         // following action should trigger generatting of SMR messages:
805         // 1) 192.0.2.5/32
806         // 2) 192.0.1.5/32
807         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
808         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
809         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
810
811         // following action should trigger generatting of SMR messages:
812         // 1) 192.0.2.5/32
813         // 2) 192.0.1.5/32
814         multiSiteScenario.storeNorthMappingNegative(SITE_C_SB, Action.Drop);
815         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
816         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
817
818         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
819         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_SB, 4);
820
821
822         //TEST CASE 3
823         // following action should trigger generatting of SMR messages:
824         // 1) 192.0.2.5/32
825         // 2) 192.0.1.5/32
826         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
827         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
828         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
829         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4);
830
831         //TEST CASE 4
832         multiSiteScenario.storeNorthMappingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
833         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
834         // following action should trigger generatting of SMR messages:
835         // 1) 192.0.2.5/32
836         // 2) 192.0.1.5/32
837         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
838         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
839
840         //TEST CASE 5
841         multiSiteScenario.deleteSouthboundMappings(SITE_D_DELETE_SB);
842         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
843         // following action should trigger generatting of SMR messages:
844         // 1) 192.0.2.5/32
845         // 2) 192.0.1.5/32
846         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
847
848         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
849
850         //TEST CASE 6
851         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
852         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
853         // following action should trigger generatting of SMR messages:
854         // 1) 192.0.2.5/32
855         // 2) 192.0.1.5/32
856         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
857
858         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB);
859         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
860         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
861
862         socketReader.stopReading();
863
864     }
865
866     // ------------------------------- Simple Tests ---------------------------
867
868     public void mapRequestSimple() throws SocketTimeoutException {
869         cleanUP();
870
871         // This Map-Request is sent from a source port different from 4342
872         // We close and bind the socket on the correct port
873         if (socket != null) {
874             socket.close();
875         }
876         socket = initSocket(socket, 56756);
877
878         sendPacket(mapRequestPacket);
879         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
880         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
881         assertEquals(4435248268955932168L, reply.getNonce().longValue());
882
883     }
884
885     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
886         cleanUP();
887         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
888
889         sleepForSeconds(2);
890         sendPacket(mapRegisterPacketWithNotify);
891         MapNotify reply = receiveMapNotify();
892         assertEquals(7, reply.getNonce().longValue());
893     }
894
895     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
896         cleanUP();
897         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
898
899         MapReply mapReply = registerAddressAndQuery(eid);
900
901         assertEquals(4, mapReply.getNonce().longValue());
902         assertEquals(locatorEid, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
903                 .getRloc());
904
905     }
906
907     public void registerAndQuery__MAC() throws SocketTimeoutException {
908         cleanUP();
909         String macAddress = "01:02:03:04:05:06";
910
911         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
912
913         assertTrue(true);
914         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
915         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
916         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
917
918         assertEquals(macAddress, macAddressFromReply);
919     }
920
921     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
922         cleanUP();
923         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
924         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
925         sleepForSeconds(1);
926
927         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
928         mapRequestBuilder.setNonce((long) 4);
929         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
930         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
931         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
932         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
933         mapRequestBuilder.getItrRloc().add(
934                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
935         sendMapRequest(mapRequestBuilder.build());
936         MapReply mapReply = receiveMapReply();
937         assertEquals(4, mapReply.getNonce().longValue());
938         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
939         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
940         mapRegisterbuilder.setWantMapNotify(true);
941         mapRegisterbuilder.setNonce((long) 8);
942         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
943         etlrBuilder.setEid(eid);
944         etlrBuilder.setRecordTtl(254);
945         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
946         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
947         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
948         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
949         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
950         mapRegisterbuilder.getMappingRecordItem().add(
951                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
952         sendMapRegister(mapRegisterbuilder.build());
953         MapNotify mapNotify = receiveMapNotify();
954         assertEquals(8, mapNotify.getNonce().longValue());
955         sleepForSeconds(1);
956         sendMapRequest(mapRequestBuilder.build());
957         mapReply = receiveMapReply();
958         assertEquals(4, mapReply.getNonce().longValue());
959         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
960                 .getLocatorRecord().get(0).getRloc());
961
962     }
963
964     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
965         cleanUP();
966         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
967         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
968         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
969         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
970         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
971         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
972         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
973         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
974                 .getRloc());
975         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
976                 .getRloc());
977     }
978
979     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
980         cleanUP();
981         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
982         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
983         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
984         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
985         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
986         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
987         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
988         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
989                 .getRloc());
990     }
991
992     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
993         cleanUP();
994         mapService.setMappingMerge(false);
995         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
996         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
997         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
998         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
999         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1000         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1001                 .getRloc());
1002     }
1003
1004     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
1005         cleanUP();
1006         mapService.setMappingMerge(true);
1007         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1008         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1009         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1010         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1011         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1012         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1013                 .get(0).getRloc();
1014         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1015                 .get(1).getRloc();
1016         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
1017                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
1018     }
1019
1020     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
1021             throws SocketTimeoutException {
1022         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1023         sleepForSeconds(1);
1024         MapRegister mb = createMapRegister(eid, rloc1);
1025         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
1026         MapRequest mr = createMapRequest(eid);
1027         MapReply mapReply = lms.handleMapRequest(mr);
1028         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
1029                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1030         mb = createMapRegister(eid, rloc2);
1031         mapNotify = lms.handleMapRegister(mb).getLeft();
1032         assertEquals(8, mapNotify.getNonce().longValue());
1033         mr = createMapRequest(eid);
1034         sendMapRequest(mr);
1035         mapReply = lms.handleMapRequest(mr);
1036         return mapReply;
1037     }
1038
1039     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
1040         cleanUP();
1041         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
1042         try {
1043             receivePacket(3000);
1044             // If didn't timeout then fail:
1045             fail();
1046         } catch (SocketTimeoutException ste) {
1047         }
1048     }
1049
1050     public void mapRegisterWithoutMapNotify() {
1051         cleanUP();
1052         sendPacket(mapRegisterPacketWithoutNotify);
1053         try {
1054             receivePacket(3000);
1055             // If didn't timeout then fail:
1056             fail();
1057         } catch (SocketTimeoutException ste) {
1058         }
1059     }
1060
1061     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
1062         cleanUP();
1063         lms.setShouldUseSmr(true);
1064         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1065         sleepForSeconds(1);
1066
1067         sendPacket(mapRegisterPacketWithNotify);
1068         receiveMapNotify();
1069
1070         sleepForSeconds(1);
1071         sendPacket(mapRequestPacket);
1072         sleepForSeconds(1);
1073
1074         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
1075         sendPacket(mapRegisterPacketWithoutNotify);
1076
1077         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
1078         MapRequest smr = MapRequestSerializer.getInstance().deserialize(readBuf, null);
1079         assertTrue(smr.isSmr());
1080         Eid sourceEid = smr.getSourceEid().getEid();
1081         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
1082         Eid smrEid = smr.getEidItem().get(0).getEid();
1083         assertTrue(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32").equals(smrEid));
1084     }
1085
1086     // --------------------- Northbound Tests ---------------------------
1087 /*
1088     private void northboundAddKey() throws Exception {
1089         cleanUP();
1090         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
1091         int mask = 32;
1092         String pass = "asdf";
1093
1094         URL url = createPutURL("key");
1095         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
1096         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
1097
1098         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
1099
1100         // Check stored password matches the one sent
1101         assertEquals(pass, retrievedKey);
1102
1103     }
1104
1105     private void northboundRetrieveSourceDestKey() throws Exception {
1106         cleanUP();
1107         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1108                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1109                 .primitiveaddress.Ipv4) LispAddressUtil
1110                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1111         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1112                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1113                 .primitiveaddress.Ipv4) LispAddressUtil
1114                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1115         int mask1 = 32;
1116         int mask2 = 32;
1117         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1118                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1119                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1120                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
1121                 .setSrcMaskLength((short) mask1)
1122                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
1123                 .setDstMaskLength((short) mask2).build();
1124         String pass = "asdf";
1125
1126         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
1127
1128         // URL url = createGetKeyIPv4URL(address1, mask1);
1129         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
1130                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
1131                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
1132                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
1133                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
1134         String reply = callURL("GET", null, "application/json", null, url);
1135         JSONTokener jt = new JSONTokener(reply);
1136         JSONObject json = new JSONObject(jt);
1137
1138         // test that the password matches what was we expected.
1139         assertEquals(pass, json.get("key"));
1140
1141     }
1142
1143     private void northboundRetrieveKey() throws Exception {
1144         cleanUP();
1145         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1146         int mask = 32;
1147         String pass = "asdf";
1148
1149         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
1150
1151         URL url = createGetKeyIPv4URL(address, mask);
1152         String reply = callURL("GET", null, "application/json", null, url);
1153         JSONTokener jt = new JSONTokener(reply);
1154         JSONObject json = new JSONObject(jt);
1155
1156         // test that the password matches what was we expected.
1157         assertEquals(pass, json.get("key"));
1158
1159     }
1160
1161     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
1162         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
1163                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
1164     }
1165
1166     private void northboundAddMapping() throws Exception {
1167         cleanUP();
1168         String pass = "asdf";
1169         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1170         int mask = 32;
1171         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1172
1173         // NB add mapping always checks the key
1174         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
1175
1176         URL url = createPutURL("mapping");
1177         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
1178         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
1179
1180         // Retrieve the RLOC from the database
1181         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1182         mapRequestBuilder.setPitr(false);
1183         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1184         mapRequestBuilder.getEidItem().add(
1185                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
1186                 LispAddressUtil.toContainer(eid)).build());
1187         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
1188
1189         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
1190                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1191                 .getLispAddressContainer());
1192
1193         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
1194
1195     }
1196
1197     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
1198         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
1199                 + "\"proxyMapReply\" : false, "
1200                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
1201                 + "{ " + "\"ipAddress\" : \""
1202                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
1203                 + "\"mapVersion\" : 0,"
1204                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
1205                 + "\"multicastPriority\" : 1,"
1206                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
1207                 + "\"afi\" : "
1208                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
1209                 + "\"rlocProbed\" : false, "
1210                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
1211                 + "\"recordTtl\" : 100" + "} " + "], "
1212                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
1213
1214         return jsonString;
1215     }
1216
1217     private void northboundRetrieveMapping() throws Exception {
1218         cleanUP();
1219         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1220         int mask = 32;
1221         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1222         // Insert mapping in the database
1223         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1224         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1225         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1226         etlr.setMaskLength((short) mask);
1227         etlr.setRecordTtl(254);
1228         etlr.setAuthoritative(false);
1229         etlr.setAction(Action.NoAction);
1230         LocatorRecordBuilder record = new LocatorRecordBuilder();
1231         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1232         record.setRouted(true);
1233         record.setRlocProbed(false);
1234         record.setLocalLocator(false);
1235         record.setPriority((short) 1);
1236         record.setWeight((short) 50);
1237         record.setMulticastPriority((short) 1);
1238         record.setMulticastWeight((short) 1);
1239         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1240         etlr.getLocatorRecord().add(record.build());
1241         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1242         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1243         lms.handleMapRegister(mapRegister.build());
1244
1245         // Get mapping using NB interface. No IID used
1246         URL url = createGetMappingIPv4URL(0, eid, mask);
1247         String reply = callURL("GET", null, "application/json", null, url);
1248         JSONTokener jt = new JSONTokener(reply);
1249         JSONObject json = new JSONObject(jt);
1250
1251         // With just one locator, locators is not a JSONArray
1252         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1253                 .getString("ipAddress");
1254
1255         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1256
1257     }
1258
1259     private void northboundDeleteMapping() throws Exception {
1260         cleanUP();
1261         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1262         int mask = 32;
1263         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1264         // Insert mapping in the database
1265         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1266         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1267         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1268         etlr.setMaskLength((short) mask);
1269         etlr.setRecordTtl(254);
1270         etlr.setAuthoritative(false);
1271         etlr.setAction(Action.NoAction);
1272         LocatorRecordBuilder record = new LocatorRecordBuilder();
1273         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1274         record.setRouted(true);
1275         record.setRlocProbed(false);
1276         record.setLocalLocator(false);
1277         record.setPriority((short) 1);
1278         record.setWeight((short) 50);
1279         record.setMulticastPriority((short) 1);
1280         record.setMulticastWeight((short) 1);
1281         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1282         etlr.getLocatorRecord().add(record.build());
1283         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1284         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1285         lms.handleMapRegister(mapRegister.build());
1286
1287         // Delete mapping using NB interface. No IID used
1288         URL url = createDeleteMappingIPv4URL(0, eid, mask);
1289         String reply = callURL("DELETE", null, "application/json", null, url);
1290
1291         // Get mapping using NB interface. No IID used
1292         url = createGetMappingIPv4URL(0, eid, mask);
1293         reply = callURL("GET", null, "application/json", null, url);
1294         JSONTokener jt = new JSONTokener(reply);
1295         JSONObject json = new JSONObject(jt);
1296
1297         // With just one locator, locators is not a JSONArray
1298         assertEquals(json.getJSONArray("locators").length(), 0);
1299     }
1300
1301     private void northboundRetrieveSourceDestMapping() throws Exception {
1302         cleanUP();
1303         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1304                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1305                 .primitiveaddress.Ipv4) LispAddressUtil
1306                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1307         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1308                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1309                 .primitiveaddress.Ipv4) LispAddressUtil
1310                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1311         int mask1 = 32;
1312         int mask2 = 32;
1313         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1314                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1315                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1316                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
1317                         address1).build()).setSrcMaskLength((short) mask1)
1318                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
1319                         address2).build()).setDstMaskLength((short) mask2).build();
1320         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1321
1322         // Insert mapping in the database
1323         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1324         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1325         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
1326         etlr.setMaskLength((short) mask1);
1327         etlr.setRecordTtl(254);
1328         etlr.setAuthoritative(false);
1329         etlr.setAction(Action.NoAction);
1330         LocatorRecordBuilder record = new LocatorRecordBuilder();
1331         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1332         record.setRouted(true);
1333         record.setRlocProbed(false);
1334         record.setLocalLocator(false);
1335         record.setPriority((short) 1);
1336         record.setWeight((short) 50);
1337         record.setMulticastPriority((short) 1);
1338         record.setMulticastWeight((short) 1);
1339         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1340         etlr.getLocatorRecord().add(record.build());
1341         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1342         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1343         lms.handleMapRegister(mapRegister.build());
1344
1345         // Get mapping using NB interface. No IID used
1346         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
1347                 address1.getIpv4Address().getIpv4Address().getValue(),
1348                 mask1,
1349                 address2.getIpv4Address().getIpv4Address().getValue(),
1350                 mask2);
1351         String reply = callURL("GET", null, "application/json", null, url);
1352         JSONTokener jt = new JSONTokener(reply);
1353         JSONObject json = new JSONObject(jt);
1354
1355         // With just one locator, locators is not a JSONArray
1356         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1357         .getString("ipAddress");
1358
1359         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1360
1361     }
1362
1363     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
1364         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
1365                 address.getAfi().shortValue(),
1366                 address.getIpv4Address().getValue(), mask);
1367         URL url = new URL(restUrl);
1368         return url;
1369     }
1370
1371     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1372             throws MalformedURLException {
1373         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1374                 "key", afi, srcAddress, srcMask,
1375                 dstAddress, dstMask);
1376         URL url = new URL(restUrl);
1377         return url;
1378     }
1379
1380     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1381             throws MalformedURLException {
1382         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1383                 "mapping", afi, srcAddress,
1384                 srcMask, dstAddress, dstMask);
1385         URL url = new URL(restUrl);
1386         return url;
1387     }
1388
1389     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1390         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1391                 iid, address.getAfi()
1392                 .shortValue(), address.getIpv4Address().getValue(), mask);
1393         URL url = new URL(restUrl);
1394         return url;
1395     }
1396
1397     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1398         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1399                 iid, address.getAfi()
1400                 .shortValue(), address.getIpv4Address().getValue(), mask);
1401         URL url = new URL(restUrl);
1402         return url;
1403     }
1404
1405     private URL createPutURL(String resource) throws MalformedURLException {
1406
1407         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
1408
1409         URL url = new URL(restUrl);
1410         return url;
1411     }
1412
1413     private String createAuthenticationString() {
1414         String authString = "admin:admin";
1415         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
1416         String authStringEnc = new String(authEncBytes);
1417         return authStringEnc;
1418     }
1419
1420     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
1421             JSONException {
1422         String authStringEnc = createAuthenticationString();
1423         connection = (HttpURLConnection) url.openConnection();
1424         connection.setRequestMethod(method);
1425         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
1426         if (content != null) {
1427             connection.setRequestProperty("Content-Type", content);
1428         }
1429         if (accept != null) {
1430             connection.setRequestProperty("Accept", accept);
1431         }
1432         if (body != null) {
1433             // now add the request body
1434             connection.setDoOutput(true);
1435             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
1436             wr.write(body);
1437             wr.flush();
1438         }
1439         connection.connect();
1440
1441         // getting the result, first check response code
1442         Integer httpResponseCode = connection.getResponseCode();
1443
1444         if (httpResponseCode > 299) {
1445             LOG.trace("HTTP Address: " + url);
1446             LOG.trace("HTTP Response Code: " + httpResponseCode);
1447             fail();
1448         }
1449
1450         InputStream is = connection.getInputStream();
1451         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
1452         StringBuilder sb = new StringBuilder();
1453         int cp;
1454         while ((cp = rd.read()) != -1) {
1455             sb.append((char) cp);
1456         }
1457         is.close();
1458         connection.disconnect();
1459         return (sb.toString());
1460     }
1461
1462     // timePeriod - in ms
1463     public void assertNoPacketReceived(int timePeriod) {
1464         try {
1465             receivePacket(timePeriod);
1466             // If didn't timeout then fail:
1467             fail();
1468         } catch (SocketTimeoutException ste) {
1469         }
1470     }
1471 */
1472     // ------------------------------- Mask Tests ---------------------------
1473
1474     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
1475         cleanUP();
1476         runPrefixTest(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/16"),
1477                 LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.2/32"),
1478                 LispAddressUtil.asIpv4PrefixBinaryEid("1.1.1.1/32"));
1479     }
1480
1481     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
1482         cleanUP();
1483         runPrefixTest(LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:6:7:8/64"),
1484                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:1:2:3/128"),
1485                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:1:2:3:1:2/128"));
1486     }
1487
1488     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
1489             throws SocketTimeoutException {
1490         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
1491         sleepForSeconds(1);
1492
1493         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1494         mapRegister.setWantMapNotify(true);
1495         mapRegister.setNonce((long) 8);
1496         mapRegister.setWantMapNotify(true);
1497         mapRegister.setKeyId((short) 0);
1498         mapRegister.setAuthenticationData(new byte[0]);
1499         mapRegister.setNonce((long) 8);
1500         mapRegister.setProxyMapReply(false);
1501         MappingRecordBuilder etlr = new MappingRecordBuilder();
1502         etlr.setRecordTtl(254);
1503         etlr.setAction(Action.NoAction);
1504         etlr.setAuthoritative(false);
1505         etlr.setMapVersion((short) 0);
1506         etlr.setEid(registerEID);
1507         etlr.setRecordTtl(254);
1508         LocatorRecordBuilder record = new LocatorRecordBuilder();
1509         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1510         record.setLocalLocator(false);
1511         record.setRlocProbed(false);
1512         record.setRouted(true);
1513         record.setMulticastPriority((short) 0);
1514         record.setMulticastWeight((short) 0);
1515         record.setPriority((short) 0);
1516         record.setWeight((short) 0);
1517         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1518         etlr.getLocatorRecord().add(record.build());
1519         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1520         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1521         sendMapRegister(mapRegister.build());
1522         MapNotify mapNotify = receiveMapNotify();
1523         assertEquals(8, mapNotify.getNonce().longValue());
1524         sleepForSeconds(1);
1525         MapRequestBuilder mapRequest = new MapRequestBuilder();
1526         mapRequest.setNonce((long) 4);
1527         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1528         mapRequest.setEidItem(new ArrayList<EidItem>());
1529         mapRequest.setAuthoritative(false);
1530         mapRequest.setMapDataPresent(false);
1531         mapRequest.setPitr(false);
1532         mapRequest.setProbe(false);
1533         mapRequest.setSmr(false);
1534         mapRequest.setSmrInvoked(false);
1535         mapRequest.getEidItem().add(new EidItemBuilder().setEid(matchedAddress).build());
1536         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
1537         mapRequest.getItrRloc().add(
1538                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1539         sendMapRequest(mapRequest.build());
1540         MapReply mapReply = receiveMapReply();
1541         assertEquals(4, mapReply.getNonce().longValue());
1542         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1543                 .get(0).getRloc());
1544         mapRequest.setEidItem(new ArrayList<EidItem>());
1545         mapRequest.getEidItem().add(new EidItemBuilder().setEid(unMatchedAddress).build());
1546         sendMapRequest(mapRequest.build());
1547         mapReply = receiveMapReply();
1548         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1549     }
1550 /*
1551     // This registers an IP with a MapRegister, then adds a password via the
1552     // northbound REST API
1553     // and checks that the password works
1554     public void testPasswordExactMatch() throws Exception {
1555         cleanUP();
1556         String ipString = "10.0.0.1";
1557         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
1558         int mask = 32;
1559         String pass = "pass";
1560
1561         URL url = createPutURL("key");
1562
1563         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
1564
1565         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
1566         LOG.trace("Address: " + address);
1567
1568         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
1569                 (byte) 31, (byte) 249, (byte) 87,
1570                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
1571                 (byte) 196, (byte) 62 };
1572
1573         byte[] zeros = new byte[20];
1574
1575         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1576
1577         // build a MapRegister
1578         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1579         mapRegister.setWantMapNotify(true);
1580         mapRegister.setNonce((long) 8);
1581         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1582         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
1583         etlr.setMaskLength((short) mask);
1584         etlr.setRecordTtl(254);
1585         LocatorRecordBuilder record = new LocatorRecordBuilder();
1586         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1587         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1588         etlr.getLocatorRecord().add(record.build());
1589         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1590         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1591
1592         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1593         mapRegister.setAuthenticationData(zeros);
1594
1595         sendMapRegister(mapRegister.build());
1596         assertNoPacketReceived(3000);
1597
1598         mapRegister.setAuthenticationData(expectedSha);
1599
1600         sendMapRegister(mapRegister.build());
1601
1602         assertMapNotifyReceived();
1603     }
1604
1605     public void testPasswordMaskMatch() throws Exception {
1606         cleanUP();
1607         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
1608         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
1609         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
1610
1611         int mask = 32;
1612         String pass = "pass";
1613
1614         URL url = createPutURL("key");
1615         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
1616
1617         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1618         // build a MapRegister
1619         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1620
1621         mapRegister.setWantMapNotify(true);
1622         mapRegister.setNonce((long) 8);
1623         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1624         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
1625         etlr.setMaskLength((short) mask);
1626         etlr.setRecordTtl(254);
1627         LocatorRecordBuilder record = new LocatorRecordBuilder();
1628         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1629         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1630         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1631         etlr.getLocatorRecord().add(record.build());
1632         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1633         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1634
1635         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1636         mapRegister
1637                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
1638                 -67, -113, 104, -110, -71 });
1639
1640         sendMapRegister(mapRegister.build());
1641
1642         assertMapNotifyReceived();
1643
1644         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
1645         mapRegister
1646                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
1647                 -71, -14, -99, 67, -23, -73 });
1648
1649         sendMapRegister(mapRegister.build());
1650         assertNoPacketReceived(3000);
1651     }
1652 */
1653     // takes an address, packs it in a MapRegister and sends it
1654     private void registerAddress(Eid eid) throws SocketTimeoutException {
1655         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1656         sleepForSeconds(1);
1657         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1658         mapRegisterBuilder.setWantMapNotify(true);
1659         mapRegisterBuilder.setKeyId((short) 0);
1660         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1661         mapRegisterBuilder.setNonce((long) 8);
1662         mapRegisterBuilder.setProxyMapReply(false);
1663         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1664         etlrBuilder.setEid(eid);
1665         etlrBuilder.setRecordTtl(254);
1666         etlrBuilder.setAction(Action.NoAction);
1667         etlrBuilder.setAuthoritative(false);
1668         etlrBuilder.setMapVersion((short) 0);
1669         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1670         recordBuilder.setLocalLocator(false);
1671         recordBuilder.setRlocProbed(false);
1672         recordBuilder.setRouted(true);
1673         recordBuilder.setMulticastPriority((short) 0);
1674         recordBuilder.setMulticastWeight((short) 0);
1675         recordBuilder.setPriority((short) 0);
1676         recordBuilder.setWeight((short) 0);
1677         recordBuilder.setRloc(locatorEid);
1678         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1679         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1680         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1681         mapRegisterBuilder.getMappingRecordItem().add(
1682                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1683         sendMapRegister(mapRegisterBuilder.build());
1684         MapNotify mapNotify = receiveMapNotify();
1685         assertEquals(8, mapNotify.getNonce().longValue());
1686     }
1687
1688     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
1689         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1690         mapRequestBuilder.setNonce((long) 4);
1691         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1692         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1693         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1694         if (srcEid != null) {
1695             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
1696         } else {
1697             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
1698                     .build());
1699         }
1700         mapRequestBuilder.getItrRloc().add(
1701                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1702         mapRequestBuilder.setAuthoritative(false);
1703         mapRequestBuilder.setMapDataPresent(false);
1704         mapRequestBuilder.setPitr(false);
1705         mapRequestBuilder.setProbe(false);
1706         mapRequestBuilder.setSmr(false);
1707         mapRequestBuilder.setSmrInvoked(false);
1708         sendMapRequest(mapRequestBuilder.build());
1709         return receiveMapReply();
1710     }
1711
1712     // takes an address, packs it in a MapRegister, sends it, returns the
1713     // MapReply
1714     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
1715         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1716         sleepForSeconds(1);
1717         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1718         mapRegisterBuilder.setWantMapNotify(true);
1719         mapRegisterBuilder.setKeyId((short) 0);
1720         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1721         mapRegisterBuilder.setNonce((long) 8);
1722         mapRegisterBuilder.setProxyMapReply(false);
1723         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1724         etlrBuilder.setEid(eid);
1725         etlrBuilder.setRecordTtl(254);
1726         etlrBuilder.setAction(Action.NoAction);
1727         etlrBuilder.setAuthoritative(false);
1728         etlrBuilder.setMapVersion((short) 0);
1729         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1730         recordBuilder.setLocalLocator(false);
1731         recordBuilder.setRlocProbed(false);
1732         recordBuilder.setRouted(true);
1733         recordBuilder.setMulticastPriority((short) 0);
1734         recordBuilder.setMulticastWeight((short) 0);
1735         recordBuilder.setPriority((short) 0);
1736         recordBuilder.setWeight((short) 0);
1737         recordBuilder.setRloc(locatorEid);
1738         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1739         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1740         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1741         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(
1742                 etlrBuilder.build()).build());
1743         sendMapRegister(mapRegisterBuilder.build());
1744         MapNotify mapNotify = receiveMapNotify();
1745         assertEquals(8, mapNotify.getNonce().longValue());
1746         // wait for the notifications to propagate
1747         sleepForSeconds(1);
1748         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1749         mapRequestBuilder.setNonce((long) 4);
1750         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1751         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1752         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1753         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1754         mapRequestBuilder.getItrRloc().add(
1755                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1756         mapRequestBuilder.setAuthoritative(false);
1757         mapRequestBuilder.setMapDataPresent(false);
1758         mapRequestBuilder.setPitr(false);
1759         mapRequestBuilder.setProbe(false);
1760         mapRequestBuilder.setSmr(false);
1761         mapRequestBuilder.setSmrInvoked(false);
1762         sendMapRequest(mapRequestBuilder.build());
1763         return receiveMapReply();
1764     }
1765
1766     // ------------------------------- LCAF Tests ---------------------------
1767
1768     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1769         cleanUP();
1770         String ipPrefix = "10.20.30.200/32";
1771         String macString = "01:02:03:04:05:06";
1772
1773         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
1774         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1775                 .ietf.inet.types.rev130715.Ipv4Prefix(ipPrefix))));
1776         builder.setDest(new SimpleAddress(new MacAddress(macString)));
1777
1778         EidBuilder eb = new EidBuilder();
1779         eb.setAddressType(SourceDestKeyLcaf.class);
1780         eb.setVirtualNetworkId(null);
1781         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1782                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
1783
1784         MapReply reply = registerAddressAndQuery(eb.build());
1785
1786         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1787         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1788         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1789
1790         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
1791         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
1792
1793         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
1794         assertNotNull(receivedAddr2.getMacAddress());
1795
1796         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
1797         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1798
1799         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
1800         assertEquals(macString, receivedMAC.getValue());
1801     }
1802
1803     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
1804         cleanUP();
1805         String ipString1 = "10.10.10.0";
1806         String ipString2 = "20.20.20.0";
1807         String ipPrefix1 = ipString1 + "/24";
1808         String ipPrefix2 = ipString2 + "/24";
1809
1810         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
1811         registerAddress(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2));
1812         registerAddress(srcDst);
1813
1814         // exact match
1815         MapReply reply = queryForAddress(srcDst, null);
1816
1817         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1818         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1819         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1820
1821         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
1822         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
1823
1824         assertNotNull(receivedAddr1.getIpv4Prefix());
1825         assertNotNull(receivedAddr2.getIpv4Prefix());
1826
1827         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
1828         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
1829
1830         // srcEid/dstEid match
1831         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "10.10.10.1");
1832         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1833         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1834
1835         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1836
1837         // dstEid match only
1838         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "1.2.3.4");
1839         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1840         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1841
1842         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1843     }
1844
1845     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1846         cleanUP();
1847         String ipString = "10.20.30.200";
1848         String macString = "01:02:03:04:05:06";
1849         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
1850         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
1851         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
1852
1853         MapReply reply = registerAddressAndQuery(kv);
1854
1855         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1856         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
1857         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
1858
1859         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
1860         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
1861
1862         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1863         assertNotNull(receivedAddr2.getMacAddress());
1864
1865         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
1866         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1867
1868         assertEquals(ipString, receivedIP.getValue());
1869         assertEquals(macString, receivedMAC.getValue());
1870     }
1871
1872     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1873         cleanUP();
1874         String macString = "01:02:03:04:05:06";
1875         String ipString = "10.20.255.30";
1876         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
1877         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1878         addresses.add(new SimpleAddress(new MacAddress(macString)));
1879         AfiListBuilder listbuilder = new AfiListBuilder();
1880         listbuilder.setAddressList(addresses);
1881
1882         EidBuilder eb = new EidBuilder();
1883         eb.setAddressType(AfiListLcaf.class);
1884         eb.setVirtualNetworkId(null);
1885         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1886                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
1887
1888         MapReply reply = registerAddressAndQuery(eb.build());
1889
1890         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1891
1892         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
1893
1894         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
1895         SimpleAddress receivedAddr1 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(0);
1896         SimpleAddress receivedAddr2 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(1);
1897
1898         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1899         assertNotNull(receivedAddr2.getMacAddress());
1900
1901         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
1902         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
1903     }
1904
1905     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
1906         cleanUP();
1907         String ipString = "10.20.255.30";
1908         int instanceId = 6;
1909
1910         EidBuilder eb = new EidBuilder();
1911         eb.setAddressType(Ipv4PrefixAfi.class);
1912         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
1913         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
1914                 .yang.ietf.inet.types.rev130715.Ipv4Prefix(ipString)).build());
1915
1916         MapReply reply = registerAddressAndQuery(eb.build());
1917
1918         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1919         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
1920
1921         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
1922
1923         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
1924     }
1925
1926     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
1927         cleanUP();
1928         String macString = "01:02:03:04:05:06";
1929         String ipString = "10.20.255.30";
1930         HopBuilder hopBuilder = new HopBuilder();
1931         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1932         hopBuilder.setLrsBits(new LrsBits(true, false, true));
1933         Hop hop1 = hopBuilder.build();
1934         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
1935         hopBuilder.setLrsBits(new LrsBits(false, true, false));
1936         Hop hop2 = hopBuilder.build();
1937         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
1938         elpBuilder.setHop(new ArrayList<Hop>());
1939         elpBuilder.getHop().add(hop1);
1940         elpBuilder.getHop().add(hop2);
1941
1942         EidBuilder eb = new EidBuilder();
1943         eb.setAddressType(ExplicitLocatorPathLcaf.class);
1944         eb.setVirtualNetworkId(null);
1945         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1946                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
1947
1948         MapReply reply = registerAddressAndQuery(eb.build());
1949
1950         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
1951                 .getAddressType());
1952
1953         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
1954                 .getMappingRecord().getEid().getAddress();
1955
1956         Hop receivedHop1 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(0);
1957         Hop receivedHop2 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(1);
1958
1959         assertEquals(true, receivedHop1.getLrsBits().isLookup());
1960         assertEquals(false, receivedHop1.getLrsBits().isRlocProbe());
1961         assertEquals(true, receivedHop1.getLrsBits().isStrict());
1962
1963         assertEquals(false, receivedHop2.getLrsBits().isLookup());
1964         assertEquals(true, receivedHop2.getLrsBits().isRlocProbe());
1965         assertEquals(false, receivedHop2.getLrsBits().isStrict());
1966
1967         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
1968         assertNotNull(receivedHop2.getAddress().getMacAddress());
1969
1970         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
1971         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
1972     }
1973
1974     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
1975         cleanUP();
1976         String ipString = "1.2.3.4";
1977         short protocol = 1;
1978         int ipTOs = 2;
1979         int localPortLow = 3;
1980         int localPortHigh = 4;
1981         int remotePortLow = 4;
1982         int remotePortHigh = 5;
1983
1984         ApplicationDataBuilder builder = new ApplicationDataBuilder();
1985         builder.setIpTos(ipTOs);
1986         builder.setProtocol(protocol);
1987         builder.setLocalPortLow(new PortNumber(localPortLow));
1988         builder.setLocalPortHigh(new PortNumber(localPortHigh));
1989         builder.setRemotePortLow(new PortNumber(remotePortLow));
1990         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
1991         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1992
1993         EidBuilder eb = new EidBuilder();
1994         eb.setAddressType(ApplicationDataLcaf.class);
1995         eb.setVirtualNetworkId(null);
1996         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1997                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
1998         Eid addressToSend = eb.build();
1999
2000         MapReply reply = registerAddressAndQuery(addressToSend);
2001
2002         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2003
2004         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
2005
2006         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
2007         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
2008         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
2009         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue()
2010                 .intValue());
2011         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue()
2012                 .intValue());
2013         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue()
2014                 .intValue());
2015         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue()
2016                 .intValue());
2017
2018         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
2019         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
2020     }
2021
2022     // ------------------- TimeOut Tests -----------
2023
2024     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
2025         cleanUP();
2026         ConfigIni.getInstance().setSmrRetryCount(0);
2027         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2028         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2029         sleepForSeconds(1);
2030         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2031         mapRequestBuilder.setNonce((long) 4);
2032         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2033         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2034         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2035         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2036         mapRequestBuilder.getItrRloc().add(
2037                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2038
2039         sendMapRequest(mapRequestBuilder.build());
2040         MapReply mapReply = receiveMapReply();
2041         assertEquals(4, mapReply.getNonce().longValue());
2042         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2043
2044         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2045         mapRegisterbuilder.setWantMapNotify(true);
2046         mapRegisterbuilder.setNonce((long) 8);
2047
2048         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2049         etlrBuilder.setEid(eid);
2050         etlrBuilder.setRecordTtl(254);
2051
2052         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2053         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2054         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2055         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2056         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2057         mapRegisterbuilder.getMappingRecordItem().add(
2058                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2059
2060         sendMapRegister(mapRegisterbuilder.build());
2061         MapNotify mapNotify = receiveMapNotify();
2062         assertEquals(8, mapNotify.getNonce().longValue());
2063         sleepForSeconds(1);
2064
2065         sendMapRequest(mapRequestBuilder.build());
2066         mapReply = receiveMapReply();
2067         assertEquals(4, mapReply.getNonce().longValue());
2068         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2069                 .getLocatorRecord().get(0).getRloc());
2070
2071         causeEntryToBeCleaned();
2072         sendMapRequest(mapRequestBuilder.build());
2073         mapReply = receiveMapReply();
2074         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2075     }
2076
2077     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
2078         cleanUP();
2079         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2080         MapRequest mapRequest = createMapRequest(eid);
2081
2082         testTTLBeforeRegister(mapRequest);
2083
2084         registerForTTL(eid);
2085
2086         testTTLAfterRegister(mapRequest);
2087
2088         causeEntryToBeCleaned();
2089         testTTLAfterClean(mapRequest);
2090
2091         //northboundAddKey();
2092         //testTTLAfterAutherize(mapRequest);
2093
2094     }
2095
2096     private void timedOutMappingRecord() {
2097         cleanUP();
2098         mapService.setMappingMerge(true);
2099         // mapping expires after 1 second
2100         ConfigIni.getInstance().setRegistrationValiditySb(1000L);
2101
2102         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32", new InstanceIdType(10L));
2103         final XtrId xtrId = new XtrId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
2104         final SiteId siteId = new SiteId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
2105
2106         final LocatorRecord locatorRecord = new LocatorRecordBuilder()
2107                 .setRloc(LispAddressUtil.asIpv4Rloc("1.1.1.1")).setLocatorId("locator-id").build();
2108         final MappingRecord mappingRecord = new MappingRecordBuilder()
2109                 .setEid(eid)
2110                 .setSiteId(siteId)
2111                 .setRecordTtl(1000)
2112                 .setXtrId(xtrId)
2113                 .setAction(Action.NoAction)
2114                 .setAuthoritative(true)
2115                 .setLocatorRecord(Lists.newArrayList()).build();
2116         mappingRecord.getLocatorRecord().add(locatorRecord);
2117
2118         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2119         mapService.addMapping(MappingOrigin.Southbound, eid, siteId,
2120                 new MappingData(mappingRecord, System.currentTimeMillis()));
2121         sleepForSeconds(2);
2122
2123         MappingRecord resultRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, eid);
2124         assertNull(resultRecord);
2125     }
2126
2127     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
2128         MapReply mapReply;
2129         sendMapRequest(mapRequest);
2130         mapReply = receiveMapReply();
2131         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2132     }
2133
2134     private void causeEntryToBeCleaned() {
2135         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
2136         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
2137         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
2138         mapService.cleanCachedMappings();
2139     }
2140
2141     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
2142         MapReply mapReply;
2143         sendMapRequest(mapRequest);
2144         mapReply = receiveMapReply();
2145         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2146                 .getLocatorRecord().get(0).getRloc());
2147         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
2148     }
2149
2150     private void registerForTTL(Eid eid) throws SocketTimeoutException {
2151         MapRegister mapRegister = createMapRegister(eid);
2152         sendMapRegister(mapRegister);
2153         assertMapNotifyReceived();
2154     }
2155
2156     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
2157         MapReply mapReply;
2158         sendMapRequest(mapRequest);
2159         mapReply = receiveMapReply();
2160         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2161     }
2162 /*
2163     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
2164         MapReply mapReply;
2165         sendMapRequest(mapRequest);
2166         mapReply = receiveMapReply();
2167         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
2168     }
2169 */
2170     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
2171         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
2172         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
2173     }
2174
2175     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
2176         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2177         mapRegisterbuilder.setWantMapNotify(true);
2178         mapRegisterbuilder.setNonce((long) 8);
2179         mapRegisterbuilder.setKeyId((short) 0);
2180         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2181         etlrBuilder.setEid(eid);
2182         etlrBuilder.setRecordTtl(254);
2183         etlrBuilder.setAuthoritative(false);
2184         etlrBuilder.setAction(Action.NoAction);
2185         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2186         recordBuilder.setRloc(rloc);
2187         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2188         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2189         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2190         mapRegisterbuilder.getMappingRecordItem().add(
2191                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2192         MapRegister mapRegister = mapRegisterbuilder.build();
2193         return mapRegister;
2194     }
2195
2196     private MapRegister createMapRegister(Eid eid) {
2197         return createMapRegister(eid, LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2198     }
2199
2200     private MapRequest createMapRequest(Eid eid) {
2201         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2202         mapRequestBuilder.setNonce((long) 4);
2203         mapRequestBuilder.setPitr(false);
2204         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2205         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2206         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2207         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2208         mapRequestBuilder.getItrRloc().add(
2209                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2210         MapRequest mr = mapRequestBuilder.build();
2211         return mr;
2212     }
2213
2214     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
2215         cleanUP();
2216         String rloc = "127.0.0.3";
2217         int port = LispMessage.PORT_NUM;
2218         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
2219         sendProxyMapRequest(rloc, port, ipRloc);
2220
2221     }
2222
2223     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
2224         cleanUP();
2225         String rloc = "127.0.0.3";
2226         int port = 4350;
2227
2228         RlocBuilder rb = new RlocBuilder();
2229         rb.setAddressType(ApplicationDataLcaf.class);
2230         rb.setVirtualNetworkId(null);
2231         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2232                 .lisp.address.address.ApplicationDataBuilder()
2233                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2234                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2235         Rloc adLcaf = rb.build();
2236
2237         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
2238         sendProxyMapRequest(rloc, port, adLcaf);
2239
2240     }
2241
2242     private class XtrRequestMappingListener implements OdlLispProtoListener {
2243
2244         @Override
2245         public void onGotMapReply(GotMapReply notification) {
2246         }
2247
2248         @Override
2249         public void onAddMapping(AddMapping notification) {
2250         }
2251
2252         @Override
2253         public void onXtrReplyMapping(XtrReplyMapping notification) {
2254         }
2255
2256         @Override
2257         public void onRequestMapping(RequestMapping notification) {
2258         }
2259
2260         @Override
2261         public void onGotMapNotify(GotMapNotify notification) {
2262         }
2263
2264         @Override
2265         public void onXtrRequestMapping(XtrRequestMapping notification) {
2266         }
2267
2268         @Override
2269         public void onMappingKeepAlive(MappingKeepAlive notification) {
2270         }
2271
2272     }
2273
2274     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
2275         cleanUP();
2276         configLispPlugin.shouldListenOnXtrPort(true);
2277         notificationCalled = false;
2278         final String eid = "10.10.10.10/32";
2279         String rloc = "127.0.0.3";
2280         int port = LispMessage.XTR_PORT_NUM;
2281
2282         RlocBuilder rb = new RlocBuilder();
2283         rb.setAddressType(ApplicationDataLcaf.class);
2284         rb.setVirtualNetworkId(null);
2285         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2286                 .lisp.address.address.ApplicationDataBuilder()
2287                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2288                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2289         Rloc adLcaf = rb.build();
2290
2291         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2292         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
2293                 new XtrRequestMappingListener() {
2294
2295             @Override
2296             public void onXtrRequestMapping(XtrRequestMapping notification) {
2297                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
2298                         .getIpv4Prefix().getValue(), eid);
2299                 notificationCalled = true;
2300                 LOG.warn("notification arrived");
2301             }
2302         });
2303         sendMapRequest(mapRequest, port);
2304         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
2305             if (notificationCalled) {
2306                 return;
2307             } else {
2308                 LOG.warn("notification hasn't arrived, sleeping...");
2309                 Thread.sleep(500);
2310             }
2311         }
2312
2313         fail("Notification hasn't arrived");
2314
2315     }
2316
2317     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
2318             SocketException {
2319         String eid = "10.1.0.1/32";
2320         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2321         sendMapRequest(mapRequest);
2322         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
2323         MapRequest receivedMapRequest = receiveMapRequest(nonProxySocket);
2324         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
2325         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
2326         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
2327         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
2328         nonProxySocket.close();
2329     }
2330
2331     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
2332         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2333         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
2334                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
2335         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
2336         sendMapRegister(mr);
2337         assertMapNotifyReceived();
2338         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2339         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
2340         builder.setPitr(true);
2341         mapRequest = builder.build();
2342         return mapRequest;
2343     }
2344
2345     private void assertMapNotifyReceived() throws SocketTimeoutException {
2346         receiveMapNotify();
2347     }
2348
2349     private MapReply receiveMapReply() throws SocketTimeoutException {
2350         return receiveMapReply(socket, 1000);
2351     }
2352
2353     private MapRequest receiveMapRequest(DatagramSocket datagramSocket) throws SocketTimeoutException {
2354         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(
2355                 datagramSocket, 30000).getData()), null);
2356     }
2357
2358     private MapNotify receiveMapNotify() throws SocketTimeoutException {
2359         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
2360     }
2361
2362     private void sendMapRequest(MapRequest mapRequest) {
2363         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
2364     }
2365
2366     private void sendMapRequest(MapRequest mapRequest, int port) {
2367         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
2368     }
2369
2370     private void sendMapRegister(MapRegister mapRegister) {
2371         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
2372     }
2373
2374     private void sendPacket(byte[] bytesToSend) {
2375         sendPacket(bytesToSend, LispMessage.PORT_NUM);
2376     }
2377
2378     private void sendPacket(byte[] bytesToSend, int port) {
2379         try {
2380             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
2381             initPacketAddress(packet, port);
2382             LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
2383             socket.send(packet);
2384         } catch (Throwable t) {
2385             fail();
2386         }
2387     }
2388
2389     private DatagramPacket receivePacket() throws SocketTimeoutException {
2390         return receivePacket(6000);
2391     }
2392
2393     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
2394         return receivePacket(socket, timeout);
2395     }
2396
2397     private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2398         try {
2399             byte[] buffer = new byte[4096];
2400             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
2401             LOG.trace("Waiting for packet from socket...");
2402             receivedSocket.setSoTimeout(timeout);
2403             receivedSocket.receive(receivePacket);
2404             LOG.trace("Received packet from socket!");
2405             return receivePacket;
2406         } catch (SocketTimeoutException ste) {
2407             throw ste;
2408         } catch (Throwable t) {
2409             fail();
2410             return null;
2411         }
2412     }
2413
2414     private MapReply receiveMapReply(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2415         DatagramPacket packet;
2416         try {
2417             while (true) {
2418                 packet = receivePacket(receivedSocket, timeout);
2419                 final ByteBuffer buff = ByteBuffer.wrap(packet.getData());
2420                 final int type = ByteUtil.getUnsignedByte(buff, LispMessage.Pos.TYPE) >> 4;
2421                 final Object lispType = MessageType.forValue(type);
2422
2423                 if (lispType == MessageType.MapReply) {
2424                     return MapReplySerializer.getInstance().deserialize(buff);
2425                 }
2426             }
2427         } catch (SocketTimeoutException ste) {
2428             throw ste;
2429         }
2430     }
2431
2432     private void sleepForSeconds(int seconds) {
2433         try {
2434             Thread.sleep(seconds*1000);
2435         } catch (InterruptedException e) {
2436             LOG.warn("Interrupted while sleeping", e);
2437         }
2438     }
2439
2440     private void sleepForMilliseconds(long milliseconds) {
2441         try {
2442             Thread.sleep(milliseconds);
2443         } catch (InterruptedException e) {
2444             LOG.warn("Interrupted while sleeping", e);
2445         }
2446     }
2447
2448     private void initPacketAddress(DatagramPacket packet, int port) throws UnknownHostException {
2449         packet.setAddress(InetAddress.getByName(lispBindAddress));
2450         packet.setPort(port);
2451     }
2452
2453     private DatagramSocket initSocket(DatagramSocket socket, int port) {
2454         for (int i=0; i < NUM_OF_ATTEMPTS_TO_CREATE_SOCKET; i++) {
2455             try {
2456                 return new DatagramSocket(new InetSocketAddress(ourAddress, port));
2457             } catch (SocketException e) {
2458                 LOG.error("Can't initialize socket for {}", ourAddress, e);
2459             }
2460         }
2461         fail();
2462         return null;
2463     }
2464
2465     private byte[] extractWSUdpByteArray(String wiresharkHex) {
2466         final int HEADER_LEN = 42;
2467         byte[] res = new byte[1000];
2468         String[] split = wiresharkHex.split(" ");
2469         int counter = 0;
2470         for (String cur : split) {
2471             cur = cur.trim();
2472             if (cur.length() == 2) {
2473                 ++counter;
2474                 if (counter > HEADER_LEN) {
2475                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
2476                 }
2477
2478             }
2479         }
2480         return Arrays.copyOf(res, counter - HEADER_LEN);
2481     }
2482
2483     private String stateToString(int state) {
2484         switch (state) {
2485         case Bundle.ACTIVE:
2486             return "ACTIVE";
2487         case Bundle.INSTALLED:
2488             return "INSTALLED";
2489         case Bundle.RESOLVED:
2490             return "RESOLVED";
2491         case Bundle.UNINSTALLED:
2492             return "UNINSTALLED";
2493         default:
2494             return "Not CONVERTED";
2495         }
2496     }
2497
2498     private void areWeReady() throws InvalidSyntaxException {
2499         sleepForSeconds(5);
2500
2501         assertNotNull(bc);
2502         boolean debugit = false;
2503         Bundle b[] = bc.getBundles();
2504         for (Bundle element : b) {
2505             int state = element.getState();
2506             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
2507                     + element.getVersion() + ", state:" + stateToString(state));
2508             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
2509                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
2510
2511                 // try {
2512                 // String host = element.getHeaders().get("FRAGMENT-HOST");
2513                 // if (host != null) {
2514                 // LOG.warn("Bundle " + element.getSymbolicName() +
2515                 // " is a fragment which is part of: " + host);
2516                 // LOG.warn("Required imports are: " +
2517                 // element.getHeaders().get("IMPORT-PACKAGE"));
2518                 // } else {
2519                 // element.start();
2520                 // }
2521                 // } catch (BundleException e) {
2522                 // LOG.error("BundleException:", e);
2523                 // fail();
2524                 // }
2525
2526                 debugit = true;
2527
2528             }
2529         }
2530         if (debugit) {
2531             LOG.warn(("Do some debugging because some bundle is unresolved"));
2532         }
2533         // assertNotNull(broker);
2534
2535         configLispPlugin.setLispAddress(lispBindAddress);
2536
2537         // Uncomment this code to Know which services were actually loaded to
2538         // BundleContext
2539
2540         /*
2541         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
2542             LOG.info(sr.getBundle().getSymbolicName());
2543             LOG.info(sr.toString());
2544         }
2545         */
2546
2547         sleepForSeconds(1);
2548     }
2549
2550     private void cleanUP() {
2551         after();
2552         mapService.cleanCachedMappings();
2553         configLispPlugin.shouldListenOnXtrPort(false);
2554         socket = initSocket(socket, LispMessage.PORT_NUM);
2555
2556     }
2557
2558     private void restartSocket() {
2559         after();
2560         socket = initSocket(socket, LispMessage.PORT_NUM);
2561     }
2562
2563 }