9696ba37cd9c5b69257bf0b61d4859d5359db5e0
[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.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.ops4j.pax.exam.CoreOptions.composite;
15 import static org.ops4j.pax.exam.CoreOptions.maven;
16 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
17
18 import java.net.DatagramPacket;
19 import java.net.DatagramSocket;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.SocketException;
23 import java.net.SocketTimeoutException;
24 import java.net.UnknownHostException;
25 import java.nio.ByteBuffer;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29
30 import javax.inject.Inject;
31
32 //import org.codehaus.jettison.json.JSONException;
33 //import org.codehaus.jettison.json.JSONObject;
34 //import org.codehaus.jettison.json.JSONTokener;
35 import org.junit.After;
36 import org.junit.Assert;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.junit.runner.RunWith;
40 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
41 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
42 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
43 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
44 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
45 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
46 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
47 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
48 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
49 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
50 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
51 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkeyBuilder;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
104 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
105 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
106 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;
107 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;
108 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;
109 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
111 import org.ops4j.pax.exam.Option;
112 import org.ops4j.pax.exam.junit.PaxExam;
113 import org.ops4j.pax.exam.util.Filter;
114 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
115 import org.ops4j.pax.exam.options.MavenUrlReference;
116 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
117 import org.ops4j.pax.exam.spi.reactors.PerClass;
118 import org.osgi.framework.Bundle;
119 import org.osgi.framework.BundleContext;
120 import org.osgi.framework.InvalidSyntaxException;
121 import org.slf4j.Logger;
122 import org.slf4j.LoggerFactory;
123
124 @RunWith(PaxExam.class)
125 @ExamReactorStrategy(PerClass.class)
126 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
127     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
128
129     private byte[] mapRequestPacket;
130     private byte[] mapRegisterPacketWithNotify;
131     private byte[] mapRegisterPacketWithoutNotify;
132     String lispBindAddress = "127.0.0.1";
133     String ourAddress = "127.0.0.2";
134     private Rloc locatorEid;
135     private DatagramSocket socket;
136     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
137
138     public static final String ODL = "org.opendaylight.controller";
139     public static final String YANG = "org.opendaylight.yangtools";
140     public static final String JERSEY = "com.sun.jersey";
141     private static final int MAX_NOTIFICATION_RETRYS = 20;
142     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(0).build();
143     private static final MappingAuthkey AUTH_KEY =
144             new MappingAuthkeyBuilder().setKeyType(1).setKeyString("password").build();
145
146     @Override
147     public String getModuleName() {
148         return "mappingservice-impl";
149     }
150
151     @Override
152     public String getInstanceName() {
153         return "mappingservice-default";
154     }
155
156     // This is temporary, since the properties in the pom file are not picked up
157     @Override
158     public String getKarafDistro() {
159         return maven()
160                 .groupId("org.opendaylight.lispflowmapping")
161                 .artifactId("distribution-karaf")
162                 .versionAsInProject()
163                 .type("zip")
164                 .getURL();
165     }
166
167     @Override
168     public MavenUrlReference getFeatureRepo() {
169         return maven()
170                 .groupId("org.opendaylight.lispflowmapping")
171                 .artifactId("features-lispflowmapping")
172                 .classifier("features")
173                 .type("xml")
174                 .versionAsInProject();
175     }
176
177     @Override
178     public String getFeatureName() {
179         return "odl-lispflowmapping-msmr";
180     }
181
182     @Override
183     public Option getLoggingOption() {
184         Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
185                 "log4j.logger.org.opendaylight.lispflowmapping",
186                 LogLevel.DEBUG.name());
187         option = composite(option, super.getLoggingOption());
188         return option;
189     }
190
191     @Test
192     public void testLispFlowMappingFeatureLoad() {
193         Assert.assertTrue(true);
194     }
195
196     @After
197     public void after() {
198         if (socket != null) {
199             socket.close();
200         }
201 //        if (connection != null) {
202 //            connection.disconnect();
203 //        }
204     }
205
206     @Before
207     public void before() throws Exception {
208         areWeReady();
209         locatorEid = LispAddressUtil.asIpv4Rloc("4.3.2.1");
210         socket = initSocket(socket, LispMessage.PORT_NUM);
211
212         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
213         // LISP(Type = 8 - Encapsulated)
214         // IP: 192.168.136.10 -> 153.16.254.1
215         // UDP: 56756
216         // LISP(Type = 1 Map-Request
217         // Record Count: 1
218         // ITR-RLOC count: 0
219         // Source EID AFI: 1
220         // Source EID 1.2.3.4
221         // Nonce: 0x3d8d2acd39c8d608
222         // ITR-RLOC AFI=1 Address=192.168.136.10
223         // Record 1: 153.16.254.1/32
224         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
225                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
226                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
227                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
228                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
229                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
230                 + "0060   00 01 99 10 fe 01"));
231
232         // IP: 192.168.136.10 -> 128.223.156.35
233         // UDP: 49289 -> 4342
234         // LISP(Type = 3 Map-Register, P=1, M=1
235         // Record Counter: 1
236         // Nonce: 0
237         // Key ID: 0x0001
238         // AuthDataLength: 20 Data:
239         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
240         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
241         // No-Action
242         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
243         // Priority/Weight: 1/100, Multicast Priority/Weight:
244         // 255/0
245         //
246
247         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String(
248                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
249                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
250                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
251                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
252                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
253                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
254                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
255
256         // IP: 192.168.136.10 -> 128.223.156.35
257         // UDP: 49289 -> 4342
258         // LISP(Type = 3 Map-Register, P=1, M=1
259         // Record Counter: 1
260         // Nonce: 7
261         // Key ID: 0x0000 NO AUTHENTICATION!!
262         // AuthDataLength: 00 Data:
263         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
264         // No-Action
265         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
266         // Priority/Weight: 1/100, Multicast Priority/Weight:
267         // 255/0
268         //
269
270         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String(
271                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
272                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
273                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
274                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
275                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
276                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
277                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
278
279         // IP: 192.168.136.10 -> 128.223.156.35
280         // UDP: 49289 -> 4342
281         // LISP(Type = 3 Map-Register, P=1, M=1
282         // Record Counter: 1
283         // Nonce: 7
284         // Key ID: 0x0000 NO AUTHENTICATION!!
285         // AuthDataLength: 00 Data:
286         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
287         // No-Action
288         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
289         // Priority/Weight: 1/100, Multicast Priority/Weight:
290         // 255/0
291         //
292
293         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String(
294                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
295                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
296                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
297                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
298                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
299                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
300                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
301     }
302
303     @Inject
304     private BundleContext bc;
305     //private HttpURLConnection connection;
306     protected static boolean notificationCalled;
307
308     @Inject @Filter(timeout=60000)
309     private IFlowMapping lms;
310
311     @Inject @Filter(timeout=60000)
312     private IMappingService mapService;
313
314     @Inject @Filter(timeout=10000)
315     private IConfigLispSouthboundPlugin configLispPlugin;
316
317     @Test
318     public void testSimpleUsage() throws Exception {
319         mapRequestSimple();
320         mapRegisterWithMapNotify();
321         mapRegisterWithMapNotifyAndMapRequest();
322         registerAndQuery__MAC();
323         mapRequestMapRegisterAndMapRequest();
324         mapRegisterWithAuthenticationWithoutConfiguringAKey();
325         mapRegisterWithoutMapNotify();
326     }
327
328     @Test
329     public void testLCAFs() throws Exception {
330         //registerAndQuery__SrcDestLCAF();
331         //registerAndQuery__SrcDestLCAFOverlap();
332         //registerAndQuery__KeyValueLCAF();
333         //registerAndQuery__ListLCAF();
334         //registerAndQuery__ApplicationData();
335         //registerAndQuery__TrafficEngineering();
336         //registerAndQuery__SegmentLCAF();
337     }
338
339     @Test
340     public void testMask() throws Exception {
341         //testPasswordExactMatch();                     TODO commented because it needs NB
342         //testPasswordMaskMatch();                      TODO commented because it needs NB
343         eidPrefixLookupIPv4();
344         eidPrefixLookupIPv6();
345     }
346 /*
347     @Test
348     public void testNorthbound() throws Exception {
349         northboundAddKey();
350         northboundAddMapping();
351         northboundDeleteMapping();
352         northboundRetrieveKey();
353         northboundRetrieveMapping();
354         northboundRetrieveSourceDestKey();
355         northboundRetrieveSourceDestMapping();
356     }
357 */
358     @Test
359     public void testOverWriting() throws Exception {
360         //testMapRegisterDosntOverwritesOtherSubKeys(); TODO weird failure, needs debug
361
362         // TODO: remove, we don't support overwrite flag any longer and RLOCs are not saved as independent RLOC groups
363         // testMapRegisterOverwritesSameSubkey();
364         // testMapRegisterOverwritesNoSubkey();
365         // testMapRegisterDoesntOverwritesNoSubkey();
366     }
367
368     @Test
369     public void testTimeOuts() throws Exception {
370         mapRequestMapRegisterAndMapRequestTestTimeout();
371         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
372     }
373
374 //    @Test
375 //    public void testNonProxy() throws Throwable {
376 //        testSimpleNonProxy();
377 //        testNonProxyOtherPort();
378 //        testRecievingNonProxyOnXtrPort();
379 //    }
380
381     @Test
382     public void testSmr() throws Exception {
383         registerQueryRegisterWithSmr();
384     }
385
386     // ------------------------------- Simple Tests ---------------------------
387
388     public void mapRequestSimple() throws SocketTimeoutException {
389         cleanUP();
390
391         // This Map-Request is sent from a source port different from 4342
392         // We close and bind the socket on the correct port
393         if (socket != null) {
394             socket.close();
395         }
396         socket = initSocket(socket, 56756);
397
398         sendPacket(mapRequestPacket);
399         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
400         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
401         assertEquals(4435248268955932168L, reply.getNonce().longValue());
402
403     }
404
405     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
406         cleanUP();
407         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixEid("153.16.254.1/32"), NULL_AUTH_KEY);
408         sleepForSeconds(1);
409         sendPacket(mapRegisterPacketWithNotify);
410         MapNotify reply = receiveMapNotify();
411         assertEquals(7, reply.getNonce().longValue());
412     }
413
414     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
415         cleanUP();
416         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
417
418         MapReply mapReply = registerAddressAndQuery(eid);
419
420         assertEquals(4, mapReply.getNonce().longValue());
421         assertEquals(locatorEid, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
422                 .getRloc());
423
424     }
425
426     public void registerAndQuery__MAC() throws SocketTimeoutException {
427         cleanUP();
428         String macAddress = "01:02:03:04:05:06";
429
430         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
431
432         assertTrue(true);
433         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
434         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
435         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
436
437         assertEquals(macAddress, macAddressFromReply);
438     }
439
440     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
441         cleanUP();
442         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
443         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
444         sleepForSeconds(1);
445
446         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
447         mapRequestBuilder.setNonce((long) 4);
448         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
449         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
450         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
451         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
452         mapRequestBuilder.getItrRloc().add(
453                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
454         sendMapRequest(mapRequestBuilder.build());
455         MapReply mapReply = receiveMapReply();
456         assertEquals(4, mapReply.getNonce().longValue());
457         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
458         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
459         mapRegisterbuilder.setWantMapNotify(true);
460         mapRegisterbuilder.setNonce((long) 8);
461         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
462         etlrBuilder.setEid(eid);
463         etlrBuilder.setRecordTtl(254);
464         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
465         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
466         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
467         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
468         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
469         mapRegisterbuilder.getMappingRecordItem().add(
470                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
471         sendMapRegister(mapRegisterbuilder.build());
472         MapNotify mapNotify = receiveMapNotify();
473         assertEquals(8, mapNotify.getNonce().longValue());
474         sleepForSeconds(1);
475         sendMapRequest(mapRequestBuilder.build());
476         mapReply = receiveMapReply();
477         assertEquals(4, mapReply.getNonce().longValue());
478         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
479                 .getLocatorRecord().get(0).getRloc());
480
481     }
482
483     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
484         cleanUP();
485         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
486         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
487         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
488         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
489         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
490         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
491         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
492         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
493                 .getRloc());
494         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
495                 .getRloc());
496     }
497
498     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
499         cleanUP();
500         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
501         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
502         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
503         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
504         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
505         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
506         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
507         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
508                 .getRloc());
509     }
510
511     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
512         cleanUP();
513         mapService.setMappingOverwrite(true);
514         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
515         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
516         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
517         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
518         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
519         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
520                 .getRloc());
521     }
522
523     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
524         cleanUP();
525         mapService.setMappingOverwrite(false);
526         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
527         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
528         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
529         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
530         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
531         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
532                 .get(0).getRloc();
533         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
534                 .get(1).getRloc();
535         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
536                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
537     }
538
539     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
540             throws SocketTimeoutException {
541         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
542         sleepForSeconds(1);
543         MapRegister mb = createMapRegister(eid, rloc1);
544         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
545         MapRequest mr = createMapRequest(eid);
546         MapReply mapReply = lms.handleMapRequest(mr);
547         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
548                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
549         mb = createMapRegister(eid, rloc2);
550         mapNotify = lms.handleMapRegister(mb).getLeft();
551         assertEquals(8, mapNotify.getNonce().longValue());
552         mr = createMapRequest(eid);
553         sendMapRequest(mr);
554         mapReply = lms.handleMapRequest(mr);
555         return mapReply;
556     }
557
558     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
559         cleanUP();
560         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
561         try {
562             receivePacket(3000);
563             // If didn't timeout then fail:
564             fail();
565         } catch (SocketTimeoutException ste) {
566         }
567     }
568
569     public void mapRegisterWithoutMapNotify() {
570         cleanUP();
571         sendPacket(mapRegisterPacketWithoutNotify);
572         try {
573             receivePacket(3000);
574             // If didn't timeout then fail:
575             fail();
576         } catch (SocketTimeoutException ste) {
577         }
578     }
579
580     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
581         cleanUP();
582         lms.setShouldUseSmr(true);
583         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixEid("153.16.254.1/32"), NULL_AUTH_KEY);
584         sleepForSeconds(1);
585
586         sendPacket(mapRegisterPacketWithNotify);
587         receiveMapNotify();
588
589         sleepForSeconds(1);
590         sendPacket(mapRequestPacket);
591         sleepForSeconds(1);
592
593         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
594         sendPacket(mapRegisterPacketWithoutNotify);
595
596         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
597         MapRequest smr = MapRequestSerializer.getInstance().deserialize(readBuf);
598         assertTrue(smr.isSmr());
599         Eid sourceEid = smr.getSourceEid().getEid();
600         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
601         Eid smrEid = smr.getEidItem().get(0).getEid();
602         assertTrue(LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32").equals(smrEid));
603     }
604
605     // --------------------- Northbound Tests ---------------------------
606 /*
607     private void northboundAddKey() throws Exception {
608         cleanUP();
609         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
610         int mask = 32;
611         String pass = "asdf";
612
613         URL url = createPutURL("key");
614         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
615         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
616
617         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
618
619         // Check stored password matches the one sent
620         assertEquals(pass, retrievedKey);
621
622     }
623
624     private void northboundRetrieveSourceDestKey() throws Exception {
625         cleanUP();
626         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
627                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
628                 .primitiveaddress.Ipv4) LispAddressUtil
629                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
630         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
631                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
632                 .primitiveaddress.Ipv4) LispAddressUtil
633                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
634         int mask1 = 32;
635         int mask2 = 32;
636         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
637                 AddressFamilyNumberEnum.LCAF.getIanaCode())
638                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
639                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
640                 .setSrcMaskLength((short) mask1)
641                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
642                 .setDstMaskLength((short) mask2).build();
643         String pass = "asdf";
644
645         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
646
647         // URL url = createGetKeyIPv4URL(address1, mask1);
648         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
649                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
650                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
651                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
652                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
653         String reply = callURL("GET", null, "application/json", null, url);
654         JSONTokener jt = new JSONTokener(reply);
655         JSONObject json = new JSONObject(jt);
656
657         // test that the password matches what was we expected.
658         assertEquals(pass, json.get("key"));
659
660     }
661
662     private void northboundRetrieveKey() throws Exception {
663         cleanUP();
664         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
665         int mask = 32;
666         String pass = "asdf";
667
668         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
669
670         URL url = createGetKeyIPv4URL(address, mask);
671         String reply = callURL("GET", null, "application/json", null, url);
672         JSONTokener jt = new JSONTokener(reply);
673         JSONObject json = new JSONObject(jt);
674
675         // test that the password matches what was we expected.
676         assertEquals(pass, json.get("key"));
677
678     }
679
680     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
681         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
682                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
683     }
684
685     private void northboundAddMapping() throws Exception {
686         cleanUP();
687         String pass = "asdf";
688         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
689         int mask = 32;
690         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
691
692         // NB add mapping always checks the key
693         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
694
695         URL url = createPutURL("mapping");
696         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
697         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
698
699         // Retrieve the RLOC from the database
700         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
701         mapRequestBuilder.setPitr(false);
702         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
703         mapRequestBuilder.getEidItem().add(
704                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
705                 LispAddressUtil.toContainer(eid)).build());
706         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
707
708         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
709                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
710                 .getLispAddressContainer());
711
712         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
713
714     }
715
716     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
717         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
718                 + "\"proxyMapReply\" : false, "
719                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
720                 + "{ " + "\"ipAddress\" : \""
721                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
722                 + "\"mapVersion\" : 0,"
723                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
724                 + "\"multicastPriority\" : 1,"
725                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
726                 + "\"afi\" : "
727                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
728                 + "\"rlocProbed\" : false, "
729                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
730                 + "\"recordTtl\" : 100" + "} " + "], "
731                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
732
733         return jsonString;
734     }
735
736     private void northboundRetrieveMapping() throws Exception {
737         cleanUP();
738         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
739         int mask = 32;
740         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
741         // Insert mapping in the database
742         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
743         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
744         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
745         etlr.setMaskLength((short) mask);
746         etlr.setRecordTtl(254);
747         etlr.setAuthoritative(false);
748         etlr.setAction(Action.NoAction);
749         LocatorRecordBuilder record = new LocatorRecordBuilder();
750         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
751         record.setRouted(true);
752         record.setRlocProbed(false);
753         record.setLocalLocator(false);
754         record.setPriority((short) 1);
755         record.setWeight((short) 50);
756         record.setMulticastPriority((short) 1);
757         record.setMulticastWeight((short) 1);
758         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
759         etlr.getLocatorRecord().add(record.build());
760         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
761         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
762         lms.handleMapRegister(mapRegister.build(), false);
763
764         // Get mapping using NB interface. No IID used
765         URL url = createGetMappingIPv4URL(0, eid, mask);
766         String reply = callURL("GET", null, "application/json", null, url);
767         JSONTokener jt = new JSONTokener(reply);
768         JSONObject json = new JSONObject(jt);
769
770         // With just one locator, locators is not a JSONArray
771         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
772                 .getString("ipAddress");
773
774         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
775
776     }
777
778     private void northboundDeleteMapping() throws Exception {
779         cleanUP();
780         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
781         int mask = 32;
782         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
783         // Insert mapping in the database
784         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
785         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
786         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
787         etlr.setMaskLength((short) mask);
788         etlr.setRecordTtl(254);
789         etlr.setAuthoritative(false);
790         etlr.setAction(Action.NoAction);
791         LocatorRecordBuilder record = new LocatorRecordBuilder();
792         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
793         record.setRouted(true);
794         record.setRlocProbed(false);
795         record.setLocalLocator(false);
796         record.setPriority((short) 1);
797         record.setWeight((short) 50);
798         record.setMulticastPriority((short) 1);
799         record.setMulticastWeight((short) 1);
800         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
801         etlr.getLocatorRecord().add(record.build());
802         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
803         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
804         lms.handleMapRegister(mapRegister.build(), false);
805
806         // Delete mapping using NB interface. No IID used
807         URL url = createDeleteMappingIPv4URL(0, eid, mask);
808         String reply = callURL("DELETE", null, "application/json", null, url);
809
810         // Get mapping using NB interface. No IID used
811         url = createGetMappingIPv4URL(0, eid, mask);
812         reply = callURL("GET", null, "application/json", null, url);
813         JSONTokener jt = new JSONTokener(reply);
814         JSONObject json = new JSONObject(jt);
815
816         // With just one locator, locators is not a JSONArray
817         assertEquals(json.getJSONArray("locators").length(), 0);
818     }
819
820     private void northboundRetrieveSourceDestMapping() throws Exception {
821         cleanUP();
822         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
823                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
824                 .primitiveaddress.Ipv4) LispAddressUtil
825                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
826         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
827                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
828                 .primitiveaddress.Ipv4) LispAddressUtil
829                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
830         int mask1 = 32;
831         int mask2 = 32;
832         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
833                 AddressFamilyNumberEnum.LCAF.getIanaCode())
834                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
835                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
836                         address1).build()).setSrcMaskLength((short) mask1)
837                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
838                         address2).build()).setDstMaskLength((short) mask2).build();
839         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
840
841         // Insert mapping in the database
842         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
843         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
844         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
845         etlr.setMaskLength((short) mask1);
846         etlr.setRecordTtl(254);
847         etlr.setAuthoritative(false);
848         etlr.setAction(Action.NoAction);
849         LocatorRecordBuilder record = new LocatorRecordBuilder();
850         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
851         record.setRouted(true);
852         record.setRlocProbed(false);
853         record.setLocalLocator(false);
854         record.setPriority((short) 1);
855         record.setWeight((short) 50);
856         record.setMulticastPriority((short) 1);
857         record.setMulticastWeight((short) 1);
858         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
859         etlr.getLocatorRecord().add(record.build());
860         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
861         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
862         lms.handleMapRegister(mapRegister.build(), false);
863
864         // Get mapping using NB interface. No IID used
865         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
866                 address1.getIpv4Address().getIpv4Address().getValue(),
867                 mask1,
868                 address2.getIpv4Address().getIpv4Address().getValue(),
869                 mask2);
870         String reply = callURL("GET", null, "application/json", null, url);
871         JSONTokener jt = new JSONTokener(reply);
872         JSONObject json = new JSONObject(jt);
873
874         // With just one locator, locators is not a JSONArray
875         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
876         .getString("ipAddress");
877
878         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
879
880     }
881
882     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
883         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
884                 address.getAfi().shortValue(),
885                 address.getIpv4Address().getValue(), mask);
886         URL url = new URL(restUrl);
887         return url;
888     }
889
890     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
891             throws MalformedURLException {
892         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
893                 "key", afi, srcAddress, srcMask,
894                 dstAddress, dstMask);
895         URL url = new URL(restUrl);
896         return url;
897     }
898
899     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
900             throws MalformedURLException {
901         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
902                 "mapping", afi, srcAddress,
903                 srcMask, dstAddress, dstMask);
904         URL url = new URL(restUrl);
905         return url;
906     }
907
908     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
909         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
910                 iid, address.getAfi()
911                 .shortValue(), address.getIpv4Address().getValue(), mask);
912         URL url = new URL(restUrl);
913         return url;
914     }
915
916     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
917         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
918                 iid, address.getAfi()
919                 .shortValue(), address.getIpv4Address().getValue(), mask);
920         URL url = new URL(restUrl);
921         return url;
922     }
923
924     private URL createPutURL(String resource) throws MalformedURLException {
925
926         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
927
928         URL url = new URL(restUrl);
929         return url;
930     }
931
932     private String createAuthenticationString() {
933         String authString = "admin:admin";
934         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
935         String authStringEnc = new String(authEncBytes);
936         return authStringEnc;
937     }
938
939     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
940             JSONException {
941         String authStringEnc = createAuthenticationString();
942         connection = (HttpURLConnection) url.openConnection();
943         connection.setRequestMethod(method);
944         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
945         if (content != null) {
946             connection.setRequestProperty("Content-Type", content);
947         }
948         if (accept != null) {
949             connection.setRequestProperty("Accept", accept);
950         }
951         if (body != null) {
952             // now add the request body
953             connection.setDoOutput(true);
954             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
955             wr.write(body);
956             wr.flush();
957         }
958         connection.connect();
959
960         // getting the result, first check response code
961         Integer httpResponseCode = connection.getResponseCode();
962
963         if (httpResponseCode > 299) {
964             LOG.trace("HTTP Address: " + url);
965             LOG.trace("HTTP Response Code: " + httpResponseCode);
966             fail();
967         }
968
969         InputStream is = connection.getInputStream();
970         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
971         StringBuilder sb = new StringBuilder();
972         int cp;
973         while ((cp = rd.read()) != -1) {
974             sb.append((char) cp);
975         }
976         is.close();
977         connection.disconnect();
978         return (sb.toString());
979     }
980
981     // timePeriod - in ms
982     public void assertNoPacketReceived(int timePeriod) {
983         try {
984             receivePacket(timePeriod);
985             // If didn't timeout then fail:
986             fail();
987         } catch (SocketTimeoutException ste) {
988         }
989     }
990 */
991     // ------------------------------- Mask Tests ---------------------------
992
993     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
994         cleanUP();
995         runPrefixTest(LispAddressUtil.asIpv4PrefixEid("1.2.3.4/16"), LispAddressUtil.asIpv4PrefixEid("1.2.3.2/32"),
996                 LispAddressUtil.asIpv4PrefixEid("1.1.1.1/32"));
997     }
998
999     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
1000         cleanUP();
1001         runPrefixTest(LispAddressUtil.asIpv6PrefixEid("1:2:3:4:5:6:7:8/64"),
1002                 LispAddressUtil.asIpv6PrefixEid("1:2:3:4:5:1:2:3/128"),
1003                 LispAddressUtil.asIpv6PrefixEid("1:2:3:1:2:3:1:2/128"));
1004     }
1005
1006     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
1007             throws SocketTimeoutException {
1008         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
1009         sleepForSeconds(1);
1010
1011         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1012         mapRegister.setWantMapNotify(true);
1013         mapRegister.setNonce((long) 8);
1014         mapRegister.setWantMapNotify(true);
1015         mapRegister.setKeyId((short) 0);
1016         mapRegister.setAuthenticationData(new byte[0]);
1017         mapRegister.setNonce((long) 8);
1018         mapRegister.setProxyMapReply(false);
1019         MappingRecordBuilder etlr = new MappingRecordBuilder();
1020         etlr.setRecordTtl(254);
1021         etlr.setAction(Action.NoAction);
1022         etlr.setAuthoritative(false);
1023         etlr.setMapVersion((short) 0);
1024         etlr.setEid(registerEID);
1025         etlr.setRecordTtl(254);
1026         LocatorRecordBuilder record = new LocatorRecordBuilder();
1027         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1028         record.setLocalLocator(false);
1029         record.setRlocProbed(false);
1030         record.setRouted(true);
1031         record.setMulticastPriority((short) 0);
1032         record.setMulticastWeight((short) 0);
1033         record.setPriority((short) 0);
1034         record.setWeight((short) 0);
1035         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1036         etlr.getLocatorRecord().add(record.build());
1037         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1038         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1039         sendMapRegister(mapRegister.build());
1040         MapNotify mapNotify = receiveMapNotify();
1041         assertEquals(8, mapNotify.getNonce().longValue());
1042         sleepForSeconds(1);
1043         MapRequestBuilder mapRequest = new MapRequestBuilder();
1044         mapRequest.setNonce((long) 4);
1045         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1046         mapRequest.setEidItem(new ArrayList<EidItem>());
1047         mapRequest.setAuthoritative(false);
1048         mapRequest.setMapDataPresent(false);
1049         mapRequest.setPitr(false);
1050         mapRequest.setProbe(false);
1051         mapRequest.setSmr(false);
1052         mapRequest.setSmrInvoked(false);
1053         mapRequest.getEidItem().add(new EidItemBuilder().setEid(matchedAddress).build());
1054         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
1055         mapRequest.getItrRloc().add(
1056                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1057         sendMapRequest(mapRequest.build());
1058         MapReply mapReply = receiveMapReply();
1059         assertEquals(4, mapReply.getNonce().longValue());
1060         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1061                 .get(0).getRloc());
1062         mapRequest.setEidItem(new ArrayList<EidItem>());
1063         mapRequest.getEidItem().add(new EidItemBuilder().setEid(unMatchedAddress).build());
1064         sendMapRequest(mapRequest.build());
1065         mapReply = receiveMapReply();
1066         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1067     }
1068 /*
1069     // This registers an IP with a MapRegister, then adds a password via the
1070     // northbound REST API
1071     // and checks that the password works
1072     public void testPasswordExactMatch() throws Exception {
1073         cleanUP();
1074         String ipString = "10.0.0.1";
1075         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
1076         int mask = 32;
1077         String pass = "pass";
1078
1079         URL url = createPutURL("key");
1080
1081         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
1082
1083         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
1084         LOG.trace("Address: " + address);
1085
1086         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
1087                 (byte) 31, (byte) 249, (byte) 87,
1088                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
1089                 (byte) 196, (byte) 62 };
1090
1091         byte[] zeros = new byte[20];
1092
1093         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1094
1095         // build a MapRegister
1096         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1097         mapRegister.setWantMapNotify(true);
1098         mapRegister.setNonce((long) 8);
1099         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1100         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
1101         etlr.setMaskLength((short) mask);
1102         etlr.setRecordTtl(254);
1103         LocatorRecordBuilder record = new LocatorRecordBuilder();
1104         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1105         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1106         etlr.getLocatorRecord().add(record.build());
1107         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1108         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1109
1110         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1111         mapRegister.setAuthenticationData(zeros);
1112
1113         sendMapRegister(mapRegister.build());
1114         assertNoPacketReceived(3000);
1115
1116         mapRegister.setAuthenticationData(expectedSha);
1117
1118         sendMapRegister(mapRegister.build());
1119
1120         assertMapNotifyReceived();
1121     }
1122
1123     public void testPasswordMaskMatch() throws Exception {
1124         cleanUP();
1125         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
1126         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
1127         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
1128
1129         int mask = 32;
1130         String pass = "pass";
1131
1132         URL url = createPutURL("key");
1133         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
1134
1135         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1136         // build a MapRegister
1137         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1138
1139         mapRegister.setWantMapNotify(true);
1140         mapRegister.setNonce((long) 8);
1141         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1142         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
1143         etlr.setMaskLength((short) mask);
1144         etlr.setRecordTtl(254);
1145         LocatorRecordBuilder record = new LocatorRecordBuilder();
1146         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1147         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1148         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1149         etlr.getLocatorRecord().add(record.build());
1150         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1151         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1152
1153         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1154         mapRegister
1155                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
1156                 -67, -113, 104, -110, -71 });
1157
1158         sendMapRegister(mapRegister.build());
1159
1160         assertMapNotifyReceived();
1161
1162         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
1163         mapRegister
1164                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
1165                 -71, -14, -99, 67, -23, -73 });
1166
1167         sendMapRegister(mapRegister.build());
1168         assertNoPacketReceived(3000);
1169     }
1170 */
1171     // takes an address, packs it in a MapRegister and sends it
1172     private void registerAddress(Eid eid) throws SocketTimeoutException {
1173         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1174         sleepForSeconds(1);
1175         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1176         mapRegisterBuilder.setWantMapNotify(true);
1177         mapRegisterBuilder.setKeyId((short) 0);
1178         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1179         mapRegisterBuilder.setNonce((long) 8);
1180         mapRegisterBuilder.setProxyMapReply(false);
1181         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1182         etlrBuilder.setEid(eid);
1183         etlrBuilder.setRecordTtl(254);
1184         etlrBuilder.setAction(Action.NoAction);
1185         etlrBuilder.setAuthoritative(false);
1186         etlrBuilder.setMapVersion((short) 0);
1187         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1188         recordBuilder.setLocalLocator(false);
1189         recordBuilder.setRlocProbed(false);
1190         recordBuilder.setRouted(true);
1191         recordBuilder.setMulticastPriority((short) 0);
1192         recordBuilder.setMulticastWeight((short) 0);
1193         recordBuilder.setPriority((short) 0);
1194         recordBuilder.setWeight((short) 0);
1195         recordBuilder.setRloc(locatorEid);
1196         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1197         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1198         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1199         mapRegisterBuilder.getMappingRecordItem().add(
1200                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1201         sendMapRegister(mapRegisterBuilder.build());
1202         MapNotify mapNotify = receiveMapNotify();
1203         assertEquals(8, mapNotify.getNonce().longValue());
1204     }
1205
1206     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
1207         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1208         mapRequestBuilder.setNonce((long) 4);
1209         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1210         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1211         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1212         if (srcEid != null) {
1213             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
1214         } else {
1215             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
1216                     .build());
1217         }
1218         mapRequestBuilder.getItrRloc().add(
1219                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1220         mapRequestBuilder.setAuthoritative(false);
1221         mapRequestBuilder.setMapDataPresent(false);
1222         mapRequestBuilder.setPitr(false);
1223         mapRequestBuilder.setProbe(false);
1224         mapRequestBuilder.setSmr(false);
1225         mapRequestBuilder.setSmrInvoked(false);
1226         sendMapRequest(mapRequestBuilder.build());
1227         return receiveMapReply();
1228     }
1229
1230     // takes an address, packs it in a MapRegister, sends it, returns the
1231     // MapReply
1232     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
1233         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1234         sleepForSeconds(1);
1235         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1236         mapRegisterBuilder.setWantMapNotify(true);
1237         mapRegisterBuilder.setKeyId((short) 0);
1238         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1239         mapRegisterBuilder.setNonce((long) 8);
1240         mapRegisterBuilder.setProxyMapReply(false);
1241         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1242         etlrBuilder.setEid(eid);
1243         etlrBuilder.setRecordTtl(254);
1244         etlrBuilder.setAction(Action.NoAction);
1245         etlrBuilder.setAuthoritative(false);
1246         etlrBuilder.setMapVersion((short) 0);
1247         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1248         recordBuilder.setLocalLocator(false);
1249         recordBuilder.setRlocProbed(false);
1250         recordBuilder.setRouted(true);
1251         recordBuilder.setMulticastPriority((short) 0);
1252         recordBuilder.setMulticastWeight((short) 0);
1253         recordBuilder.setPriority((short) 0);
1254         recordBuilder.setWeight((short) 0);
1255         recordBuilder.setRloc(locatorEid);
1256         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1257         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1258         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1259         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(
1260                 etlrBuilder.build()).build());
1261         sendMapRegister(mapRegisterBuilder.build());
1262         MapNotify mapNotify = receiveMapNotify();
1263         assertEquals(8, mapNotify.getNonce().longValue());
1264         // wait for the notifications to propagate
1265         sleepForSeconds(1);
1266         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1267         mapRequestBuilder.setNonce((long) 4);
1268         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1269         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1270         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1271         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1272         mapRequestBuilder.getItrRloc().add(
1273                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1274         mapRequestBuilder.setAuthoritative(false);
1275         mapRequestBuilder.setMapDataPresent(false);
1276         mapRequestBuilder.setPitr(false);
1277         mapRequestBuilder.setProbe(false);
1278         mapRequestBuilder.setSmr(false);
1279         mapRequestBuilder.setSmrInvoked(false);
1280         sendMapRequest(mapRequestBuilder.build());
1281         return receiveMapReply();
1282     }
1283
1284     // ------------------------------- LCAF Tests ---------------------------
1285
1286     @Test
1287     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1288         cleanUP();
1289         String ipPrefix = "10.20.30.200/32";
1290         String macString = "01:02:03:04:05:06";
1291
1292         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
1293         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1294                 .ietf.inet.types.rev100924.Ipv4Prefix(ipPrefix))));
1295         builder.setDest(new SimpleAddress(new MacAddress(macString)));
1296
1297         EidBuilder eb = new EidBuilder();
1298         eb.setAddressType(SourceDestKeyLcaf.class);
1299         eb.setVirtualNetworkId(null);
1300         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1301                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
1302
1303         MapReply reply = registerAddressAndQuery(eb.build());
1304
1305         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1306         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1307         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1308
1309         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
1310         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
1311
1312         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
1313         assertNotNull(receivedAddr2.getMacAddress());
1314
1315         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
1316         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1317
1318         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
1319         assertEquals(macString, receivedMAC.getValue());
1320     }
1321
1322     @Test
1323     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
1324         cleanUP();
1325         String ipString1 = "10.10.10.0";
1326         String ipString2 = "20.20.20.0";
1327         String ipPrefix1 = ipString1 + "/24";
1328         String ipPrefix2 = ipString2 + "/24";
1329
1330         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
1331         registerAddress(LispAddressUtil.asIpv4PrefixEid(ipPrefix2));
1332         registerAddress(srcDst);
1333
1334         // exact match
1335         MapReply reply = queryForAddress(srcDst, null);
1336
1337         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1338         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1339         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1340
1341         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
1342         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
1343
1344         assertNotNull(receivedAddr1.getIpv4Prefix());
1345         assertNotNull(receivedAddr2.getIpv4Prefix());
1346
1347         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
1348         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
1349
1350         // srcEid/dstEid match
1351         reply = queryForAddress(LispAddressUtil.asIpv4PrefixEid("20.20.20.1/32"), "10.10.10.1");
1352         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1353         assertEquals(Ipv4PrefixAfi.class, fromNetwork.getAddressType());
1354
1355         Ipv4Prefix ipAddr2 = (Ipv4Prefix) fromNetwork.getAddress();
1356         assertEquals(ipPrefix2, ipAddr2.getIpv4Prefix().getValue());
1357
1358         // dstEid match only
1359         reply = queryForAddress(LispAddressUtil.asIpv4PrefixEid("20.20.20.1/32"), "1.2.3.4");
1360         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1361         assertEquals(Ipv4PrefixAfi.class, fromNetwork.getAddressType());
1362
1363         ipAddr2 = (Ipv4Prefix) fromNetwork.getAddress();
1364         assertEquals(ipPrefix2, ipAddr2.getIpv4Prefix().getValue());
1365     }
1366
1367     @Test
1368     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1369         cleanUP();
1370         String ipString = "10.20.30.200";
1371         String macString = "01:02:03:04:05:06";
1372         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
1373         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
1374         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
1375
1376         MapReply reply = registerAddressAndQuery(kv);
1377
1378         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1379         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
1380         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
1381
1382         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
1383         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
1384
1385         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1386         assertNotNull(receivedAddr2.getMacAddress());
1387
1388         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
1389         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1390
1391         assertEquals(ipString, receivedIP.getValue());
1392         assertEquals(macString, receivedMAC.getValue());
1393     }
1394
1395     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1396         cleanUP();
1397         String macString = "01:02:03:04:05:06";
1398         String ipString = "10.20.255.30";
1399         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
1400         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1401         addresses.add(new SimpleAddress(new MacAddress(macString)));
1402         AfiListBuilder listbuilder = new AfiListBuilder();
1403         listbuilder.setAddressList(addresses);
1404
1405         EidBuilder eb = new EidBuilder();
1406         eb.setAddressType(AfiListLcaf.class);
1407         eb.setVirtualNetworkId(null);
1408         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1409                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
1410
1411         MapReply reply = registerAddressAndQuery(eb.build());
1412
1413         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1414
1415         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
1416
1417         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
1418         SimpleAddress receivedAddr1 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(0);
1419         SimpleAddress receivedAddr2 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(1);
1420
1421         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1422         assertNotNull(receivedAddr2.getMacAddress());
1423
1424         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
1425         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
1426     }
1427
1428     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
1429         cleanUP();
1430         String ipString = "10.20.255.30";
1431         int instanceId = 6;
1432
1433         EidBuilder eb = new EidBuilder();
1434         eb.setAddressType(Ipv4PrefixAfi.class);
1435         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
1436         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
1437                 .yang.ietf.inet.types.rev100924.Ipv4Prefix(ipString)).build());
1438
1439         MapReply reply = registerAddressAndQuery(eb.build());
1440
1441         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1442         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
1443
1444         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
1445
1446         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
1447     }
1448
1449     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
1450         cleanUP();
1451         String macString = "01:02:03:04:05:06";
1452         String ipString = "10.20.255.30";
1453         HopBuilder hopBuilder = new HopBuilder();
1454         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1455         hopBuilder.setLrsBits(new LrsBits(true, false, true));
1456         Hop hop1 = hopBuilder.build();
1457         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
1458         hopBuilder.setLrsBits(new LrsBits(false, true, false));
1459         Hop hop2 = hopBuilder.build();
1460         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
1461         elpBuilder.setHop(new ArrayList<Hop>());
1462         elpBuilder.getHop().add(hop1);
1463         elpBuilder.getHop().add(hop2);
1464
1465         EidBuilder eb = new EidBuilder();
1466         eb.setAddressType(ExplicitLocatorPathLcaf.class);
1467         eb.setVirtualNetworkId(null);
1468         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1469                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
1470
1471         MapReply reply = registerAddressAndQuery(eb.build());
1472
1473         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
1474                 .getAddressType());
1475
1476         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
1477                 .getMappingRecord().getEid().getAddress();
1478
1479         Hop receivedHop1 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(0);
1480         Hop receivedHop2 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(1);
1481
1482         assertEquals(true, receivedHop1.getLrsBits().isLookup());
1483         assertEquals(false, receivedHop1.getLrsBits().isRlocProbe());
1484         assertEquals(true, receivedHop1.getLrsBits().isStrict());
1485
1486         assertEquals(false, receivedHop2.getLrsBits().isLookup());
1487         assertEquals(true, receivedHop2.getLrsBits().isRlocProbe());
1488         assertEquals(false, receivedHop2.getLrsBits().isStrict());
1489
1490         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
1491         assertNotNull(receivedHop2.getAddress().getMacAddress());
1492
1493         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
1494         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
1495     }
1496
1497     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
1498         cleanUP();
1499         String ipString = "1.2.3.4";
1500         short protocol = 1;
1501         int ipTOs = 2;
1502         int localPortLow = 3;
1503         int localPortHigh = 4;
1504         int remotePortLow = 4;
1505         int remotePortHigh = 5;
1506
1507         ApplicationDataBuilder builder = new ApplicationDataBuilder();
1508         builder.setIpTos(ipTOs);
1509         builder.setProtocol(protocol);
1510         builder.setLocalPortLow(new PortNumber(localPortLow));
1511         builder.setLocalPortHigh(new PortNumber(localPortHigh));
1512         builder.setRemotePortLow(new PortNumber(remotePortLow));
1513         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
1514         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1515
1516         EidBuilder eb = new EidBuilder();
1517         eb.setAddressType(ApplicationDataLcaf.class);
1518         eb.setVirtualNetworkId(null);
1519         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1520                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
1521         Eid addressToSend = eb.build();
1522
1523         MapReply reply = registerAddressAndQuery(addressToSend);
1524
1525         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1526
1527         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
1528
1529         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
1530         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
1531         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
1532         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue()
1533                 .intValue());
1534         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue()
1535                 .intValue());
1536         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue()
1537                 .intValue());
1538         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue()
1539                 .intValue());
1540
1541         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
1542         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
1543     }
1544
1545     // ------------------- TimeOut Tests -----------
1546
1547     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
1548         cleanUP();
1549         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
1550         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1551         sleepForSeconds(1);
1552         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1553         mapRequestBuilder.setNonce((long) 4);
1554         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
1555         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1556         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1557         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1558         mapRequestBuilder.getItrRloc().add(
1559                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1560
1561         sendMapRequest(mapRequestBuilder.build());
1562         MapReply mapReply = receiveMapReply();
1563         assertEquals(4, mapReply.getNonce().longValue());
1564         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1565
1566         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1567         mapRegisterbuilder.setWantMapNotify(true);
1568         mapRegisterbuilder.setNonce((long) 8);
1569
1570         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1571         etlrBuilder.setEid(eid);
1572         etlrBuilder.setMaskLength((short) 32);
1573         etlrBuilder.setRecordTtl(254);
1574
1575         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1576         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1577         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1578         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1579         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1580         mapRegisterbuilder.getMappingRecordItem().add(
1581                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1582
1583         sendMapRegister(mapRegisterbuilder.build());
1584         MapNotify mapNotify = receiveMapNotify();
1585         assertEquals(8, mapNotify.getNonce().longValue());
1586         sleepForSeconds(1);
1587
1588         sendMapRequest(mapRequestBuilder.build());
1589         mapReply = receiveMapReply();
1590         assertEquals(4, mapReply.getNonce().longValue());
1591         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
1592                 .getLocatorRecord().get(0).getRloc());
1593
1594         causeEntryToBeCleaned();
1595         sendMapRequest(mapRequestBuilder.build());
1596         mapReply = receiveMapReply();
1597         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1598     }
1599
1600     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
1601         cleanUP();
1602         Eid eid = LispAddressUtil.asIpv6PrefixEid("1.2.3.4/32");
1603         MapRequest mapRequest = createMapRequest(eid);
1604
1605         testTTLBeforeRegister(mapRequest);
1606
1607         registerForTTL(eid);
1608
1609         testTTLAfterRegister(mapRequest);
1610
1611         causeEntryToBeCleaned();
1612         testTTLAfterClean(mapRequest);
1613
1614         //northboundAddKey();
1615         //testTTLAfterAutherize(mapRequest);
1616
1617     }
1618
1619     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
1620         MapReply mapReply;
1621         sendMapRequest(mapRequest);
1622         mapReply = receiveMapReply();
1623         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1624     }
1625
1626     private void causeEntryToBeCleaned() {
1627         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
1628         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
1629         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
1630         mapService.cleanCachedMappings();
1631     }
1632
1633     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
1634         MapReply mapReply;
1635         sendMapRequest(mapRequest);
1636         mapReply = receiveMapReply();
1637         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
1638                 .getLocatorRecord().get(0).getRloc());
1639         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
1640     }
1641
1642     private void registerForTTL(Eid eid) throws SocketTimeoutException {
1643         MapRegister mapRegister = createMapRegister(eid);
1644         sendMapRegister(mapRegister);
1645         assertMapNotifyReceived();
1646     }
1647
1648     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
1649         MapReply mapReply;
1650         sendMapRequest(mapRequest);
1651         mapReply = receiveMapReply();
1652         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1653     }
1654 /*
1655     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
1656         MapReply mapReply;
1657         sendMapRequest(mapRequest);
1658         mapReply = receiveMapReply();
1659         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
1660     }
1661 */
1662     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
1663         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
1664         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
1665     }
1666
1667     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
1668         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1669         mapRegisterbuilder.setWantMapNotify(true);
1670         mapRegisterbuilder.setNonce((long) 8);
1671         mapRegisterbuilder.setKeyId((short) 0);
1672         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1673         etlrBuilder.setEid(eid);
1674         etlrBuilder.setMaskLength((short) 24);
1675         etlrBuilder.setRecordTtl(254);
1676         etlrBuilder.setAuthoritative(false);
1677         etlrBuilder.setAction(Action.NoAction);
1678         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1679         recordBuilder.setRloc(rloc);
1680         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1681         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1682         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1683         mapRegisterbuilder.getMappingRecordItem().add(
1684                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1685         MapRegister mapRegister = mapRegisterbuilder.build();
1686         return mapRegister;
1687     }
1688
1689     private MapRegister createMapRegister(Eid eid) {
1690         return createMapRegister(eid, LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1691     }
1692
1693     private MapRequest createMapRequest(Eid eid) {
1694         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1695         mapRequestBuilder.setNonce((long) 4);
1696         mapRequestBuilder.setPitr(false);
1697         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
1698         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1699         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1700         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1701         mapRequestBuilder.getItrRloc().add(
1702                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1703         MapRequest mr = mapRequestBuilder.build();
1704         return mr;
1705     }
1706
1707     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
1708         cleanUP();
1709         String rloc = "127.0.0.3";
1710         int port = LispMessage.PORT_NUM;
1711         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
1712         sendProxyMapRequest(rloc, port, ipRloc);
1713
1714     }
1715
1716     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
1717         cleanUP();
1718         String rloc = "127.0.0.3";
1719         int port = 4350;
1720
1721         RlocBuilder rb = new RlocBuilder();
1722         rb.setAddressType(ApplicationDataLcaf.class);
1723         rb.setVirtualNetworkId(null);
1724         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1725                 .lisp.address.address.ApplicationDataBuilder()
1726                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
1727                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
1728         Rloc adLcaf = rb.build();
1729
1730         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
1731         sendProxyMapRequest(rloc, port, adLcaf);
1732
1733     }
1734
1735     private class XtrRequestMappingListener implements OdlLispProtoListener {
1736
1737         @Override
1738         public void onGotMapReply(GotMapReply notification) {
1739         }
1740
1741         @Override
1742         public void onAddMapping(AddMapping notification) {
1743         }
1744
1745         @Override
1746         public void onXtrReplyMapping(XtrReplyMapping notification) {
1747         }
1748
1749         @Override
1750         public void onRequestMapping(RequestMapping notification) {
1751         }
1752
1753         @Override
1754         public void onGotMapNotify(GotMapNotify notification) {
1755         }
1756
1757         @Override
1758         public void onXtrRequestMapping(XtrRequestMapping notification) {
1759         }
1760
1761     }
1762
1763     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
1764         cleanUP();
1765         configLispPlugin.shouldListenOnXtrPort(true);
1766         notificationCalled = false;
1767         final String eid = "10.10.10.10/32";
1768         String rloc = "127.0.0.3";
1769         int port = LispMessage.XTR_PORT_NUM;
1770
1771         RlocBuilder rb = new RlocBuilder();
1772         rb.setAddressType(ApplicationDataLcaf.class);
1773         rb.setVirtualNetworkId(null);
1774         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1775                 .lisp.address.address.ApplicationDataBuilder()
1776                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
1777                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
1778         Rloc adLcaf = rb.build();
1779
1780         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
1781         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
1782                 new XtrRequestMappingListener() {
1783
1784             @Override
1785             public void onXtrRequestMapping(XtrRequestMapping notification) {
1786                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
1787                         .getIpv4Prefix().getValue(), eid);
1788                 notificationCalled = true;
1789                 LOG.warn("notification arrived");
1790             }
1791         });
1792         sendMapRequest(mapRequest, port);
1793         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
1794             if (notificationCalled) {
1795                 return;
1796             } else {
1797                 LOG.warn("notification hasn't arrived, sleeping...");
1798                 Thread.sleep(500);
1799             }
1800         }
1801
1802         fail("Notification hasn't arrived");
1803
1804     }
1805
1806     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
1807             SocketException {
1808         String eid = "10.1.0.1/32";
1809         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
1810         sendMapRequest(mapRequest);
1811         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
1812         MapRequest receivedMapRequest = receiveMapRequest(nonProxySocket);
1813         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
1814         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
1815         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
1816         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
1817         nonProxySocket.close();
1818     }
1819
1820     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
1821         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixEid(eid));
1822         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
1823                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
1824         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
1825         sendMapRegister(mr);
1826         assertMapNotifyReceived();
1827         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixEid(eid));
1828         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
1829         builder.setPitr(true);
1830         mapRequest = builder.build();
1831         return mapRequest;
1832     }
1833
1834     private void assertMapNotifyReceived() throws SocketTimeoutException {
1835         receiveMapNotify();
1836     }
1837
1838     private MapReply receiveMapReply() throws SocketTimeoutException {
1839         return MapReplySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1840     }
1841
1842     private MapRequest receiveMapRequest(DatagramSocket datagramSocket) throws SocketTimeoutException {
1843         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(
1844                 datagramSocket, 30000).getData()));
1845     }
1846
1847     private MapNotify receiveMapNotify() throws SocketTimeoutException {
1848         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1849     }
1850
1851     private void sendMapRequest(MapRequest mapRequest) {
1852         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
1853     }
1854
1855     private void sendMapRequest(MapRequest mapRequest, int port) {
1856         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
1857     }
1858
1859     private void sendMapRegister(MapRegister mapRegister) {
1860         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
1861     }
1862
1863     private void sendPacket(byte[] bytesToSend) {
1864         sendPacket(bytesToSend, LispMessage.PORT_NUM);
1865     }
1866
1867     private void sendPacket(byte[] bytesToSend, int port) {
1868         try {
1869             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
1870             initPacketAddress(packet, port);
1871             LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
1872             socket.send(packet);
1873         } catch (Throwable t) {
1874             fail();
1875         }
1876     }
1877
1878     private DatagramPacket receivePacket() throws SocketTimeoutException {
1879         return receivePacket(6000);
1880     }
1881
1882     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
1883         return receivePacket(socket, timeout);
1884     }
1885
1886     private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
1887         try {
1888             byte[] buffer = new byte[4096];
1889             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
1890             LOG.trace("Waiting for packet from socket...");
1891             receivedSocket.setSoTimeout(timeout);
1892             receivedSocket.receive(receivePacket);
1893             LOG.trace("Received packet from socket!");
1894             return receivePacket;
1895         } catch (SocketTimeoutException ste) {
1896             throw ste;
1897         } catch (Throwable t) {
1898             fail();
1899             return null;
1900         }
1901     }
1902
1903     private void sleepForSeconds(int seconds) {
1904         try {
1905             Thread.sleep(seconds*1000);
1906         } catch (InterruptedException e) {
1907             LOG.warn("Interrupted while sleeping", e);
1908         }
1909     }
1910
1911     private void initPacketAddress(DatagramPacket packet, int port) throws UnknownHostException {
1912         packet.setAddress(InetAddress.getByName(lispBindAddress));
1913         packet.setPort(port);
1914     }
1915
1916     private DatagramSocket initSocket(DatagramSocket socket, int port) {
1917         try {
1918             socket = new DatagramSocket(new InetSocketAddress(ourAddress, port));
1919         } catch (SocketException e) {
1920             e.printStackTrace();
1921             fail();
1922         }
1923         return socket;
1924     }
1925
1926     private byte[] extractWSUdpByteArray(String wiresharkHex) {
1927         final int HEADER_LEN = 42;
1928         byte[] res = new byte[1000];
1929         String[] split = wiresharkHex.split(" ");
1930         int counter = 0;
1931         for (String cur : split) {
1932             cur = cur.trim();
1933             if (cur.length() == 2) {
1934                 ++counter;
1935                 if (counter > HEADER_LEN) {
1936                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
1937                 }
1938
1939             }
1940         }
1941         return Arrays.copyOf(res, counter - HEADER_LEN);
1942     }
1943
1944     private String stateToString(int state) {
1945         switch (state) {
1946         case Bundle.ACTIVE:
1947             return "ACTIVE";
1948         case Bundle.INSTALLED:
1949             return "INSTALLED";
1950         case Bundle.RESOLVED:
1951             return "RESOLVED";
1952         case Bundle.UNINSTALLED:
1953             return "UNINSTALLED";
1954         default:
1955             return "Not CONVERTED";
1956         }
1957     }
1958
1959     private void areWeReady() throws InvalidSyntaxException {
1960         sleepForSeconds(5);
1961
1962         assertNotNull(bc);
1963         boolean debugit = false;
1964         Bundle b[] = bc.getBundles();
1965         for (Bundle element : b) {
1966             int state = element.getState();
1967             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
1968                     + element.getVersion() + ", state:" + stateToString(state));
1969             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
1970                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
1971
1972                 // try {
1973                 // String host = element.getHeaders().get("FRAGMENT-HOST");
1974                 // if (host != null) {
1975                 // LOG.warn("Bundle " + element.getSymbolicName() +
1976                 // " is a fragment which is part of: " + host);
1977                 // LOG.warn("Required imports are: " +
1978                 // element.getHeaders().get("IMPORT-PACKAGE"));
1979                 // } else {
1980                 // element.start();
1981                 // }
1982                 // } catch (BundleException e) {
1983                 // LOG.error("BundleException:", e);
1984                 // fail();
1985                 // }
1986
1987                 debugit = true;
1988
1989             }
1990         }
1991         if (debugit) {
1992             LOG.warn(("Do some debugging because some bundle is unresolved"));
1993         }
1994         // assertNotNull(broker);
1995
1996         configLispPlugin.setLispAddress(lispBindAddress);
1997
1998         // Uncomment this code to Know which services were actually loaded to
1999         // BundleContext
2000
2001         /*
2002         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
2003             LOG.info(sr.getBundle().getSymbolicName());
2004             LOG.info(sr.toString());
2005         }
2006         */
2007
2008         sleepForSeconds(1);
2009     }
2010
2011     private void cleanUP() {
2012         after();
2013         mapService.cleanCachedMappings();
2014         configLispPlugin.shouldListenOnXtrPort(false);
2015         socket = initSocket(socket, LispMessage.PORT_NUM);
2016
2017     }
2018
2019 }