added keyvalue and map reply encapsulated in map request serialization
[lispflowmapping.git] / mappingservice / 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.options;
15
16 import java.io.BufferedReader;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.InputStreamReader;
20 import java.io.OutputStreamWriter;
21 import java.net.DatagramPacket;
22 import java.net.DatagramSocket;
23 import java.net.HttpURLConnection;
24 import java.net.InetAddress;
25 import java.net.InetSocketAddress;
26 import java.net.MalformedURLException;
27 import java.net.SocketException;
28 import java.net.SocketTimeoutException;
29 import java.net.URL;
30 import java.net.UnknownHostException;
31 import java.nio.ByteBuffer;
32 import java.nio.charset.Charset;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.concurrent.TimeUnit;
36
37 import javax.inject.Inject;
38
39 import org.apache.commons.codec.binary.Base64;
40 import org.codehaus.jettison.json.JSONException;
41 import org.codehaus.jettison.json.JSONObject;
42 import org.codehaus.jettison.json.JSONTokener;
43 import org.junit.After;
44 import org.junit.Before;
45 import org.junit.Test;
46 import org.junit.runner.RunWith;
47 import org.opendaylight.lispflowmapping.clusterdao.ClusterDAOService;
48 import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
49 import org.opendaylight.lispflowmapping.implementation.serializer.MapNotifySerializer;
50 import org.opendaylight.lispflowmapping.implementation.serializer.MapRegisterSerializer;
51 import org.opendaylight.lispflowmapping.implementation.serializer.MapReplySerializer;
52 import org.opendaylight.lispflowmapping.implementation.serializer.MapRequestSerializer;
53 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
54 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
55 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
56 import org.opendaylight.lispflowmapping.type.AddressFamilyNumberEnum;
57 import org.opendaylight.lispflowmapping.type.LispCanonicalAddressFormatEnum;
58 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispPlugin;
59 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafApplicationDataAddress;
60 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafKeyValueAddress;
61 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafListAddress;
62 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafSegmentAddress;
63 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafSourceDestAddress;
64 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LcafTrafficEngineeringAddress;
65 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispAFIAddress;
66 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispIpv4Address;
67 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.LispMacAddress;
68 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapNotify;
69 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRegister;
70 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapReply;
71 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRequest;
72 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.ReencapHop;
73 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidrecords.EidRecord;
74 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidrecords.EidRecordBuilder;
75 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecord;
76 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecord.Action;
77 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecordBuilder;
78 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafkeyvalueaddress.KeyBuilder;
79 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafkeyvalueaddress.ValueBuilder;
80 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcaflistaddress.Addresses;
81 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcaflistaddress.AddressesBuilder;
82 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafsegmentaddress.AddressBuilder;
83 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafsourcedestaddress.DstAddressBuilder;
84 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafsourcedestaddress.SrcAddressBuilder;
85 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcaftrafficengineeringaddress.Hops;
86 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcaftrafficengineeringaddress.HopsBuilder;
87 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.LispAddressContainer;
88 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.Ipv4;
89 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.Ipv4Builder;
90 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafApplicationDataBuilder;
91 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafKeyValueBuilder;
92 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafListBuilder;
93 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafSegmentBuilder;
94 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafSourceDest;
95 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafSourceDestBuilder;
96 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafTrafficEngineeringBuilder;
97 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.Mac;
98 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.MacBuilder;
99 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.NoBuilder;
100 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.locatorrecords.LocatorRecord;
101 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.locatorrecords.LocatorRecordBuilder;
102 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.mapregisternotification.MapRegisterBuilder;
103 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.ItrRloc;
104 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.ItrRlocBuilder;
105 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.SourceEidBuilder;
106 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequestnotification.MapRequestBuilder;
107 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.reencaphop.Hop;
108 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.reencaphop.HopBuilder;
109 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
112 import org.ops4j.pax.exam.Configuration;
113 import org.ops4j.pax.exam.Option;
114 import org.ops4j.pax.exam.junit.PaxExam;
115 import org.osgi.framework.Bundle;
116 import org.osgi.framework.BundleContext;
117 import org.osgi.framework.BundleException;
118 import org.osgi.framework.InvalidSyntaxException;
119 import org.osgi.framework.ServiceReference;
120 import org.slf4j.Logger;
121 import org.slf4j.LoggerFactory;
122
123 import aQute.lib.osgi.Constants;
124
125 @RunWith(PaxExam.class)
126 public class MappingServiceIntegrationTest {
127
128     private IFlowMapping lms;
129     private ClusterDAOService clusterService;
130     protected static final Logger logger = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
131     private byte[] mapRequestPacket;
132     private byte[] mapRegisterPacketWithNotify;
133     private byte[] mapRegisterPacketWithoutNotify;
134     private IConfigLispPlugin configLispPlugin;
135     int lispPortNumber = LispMessage.PORT_NUM;
136     String lispBindAddress = "127.0.0.1";
137     String ourAddress = "127.0.0.2";
138     private LispAFIAddress locatorEid;
139     private DatagramSocket socket;
140     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
141
142     public static final String ODL = "org.opendaylight.controller";
143     public static final String YANG = "org.opendaylight.yangtools";
144     public static final String JERSEY = "com.sun.jersey";
145     private static final int MAX_SERVICE_LOAD_RETRIES = 45;
146
147     @After
148     public void after() {
149         if (socket != null) {
150             socket.close();
151         }
152         if (connection != null) {
153             connection.disconnect();
154         }
155     }
156
157     @Before
158     public void before() throws Exception {
159         areWeReady();
160         locatorEid = asIPAfiAddress("4.3.2.1");
161         socket = initSocket(socket);
162
163         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
164         // LISP(Type = 8 - Encapsulated)
165         // IP: 192.168.136.10 -> 1.2.3.4
166         // UDP: 56756
167         // LISP(Type = 1 Map-Request
168         // Record Count: 1
169         // ITR-RLOC count: 0
170         // Source EID AFI: 0
171         // Source EID not present
172         // Nonce: 0x3d8d2acd39c8d608
173         // ITR-RLOC AFI=1 Address=192.168.136.10
174         // Record 1: 1.2.3.4/32
175         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
176                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
177                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
178                 + "0030   00 38 d4 31 00 00 ff 11 56 f3 7f 00 00 02 01 02 "
179                 + "0040   03 04 dd b4 10 f6 00 24 ef 3a 10 00 00 01 3d 8d "
180                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
181                 + "0060   00 01 01 02 03 04"));
182
183         // IP: 192.168.136.10 -> 128.223.156.35
184         // UDP: 49289 -> 4342
185         // LISP(Type = 3 Map-Register, P=1, M=1
186         // Record Counter: 1
187         // Nonce: 0
188         // Key ID: 0x0001
189         // AuthDataLength: 20 Data:
190         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
191         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
192         // No-Action
193         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
194         // Priority/Weight: 1/100, Multicast Priority/Weight:
195         // 255/0
196         //
197
198         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
199                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
200                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
201                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
202                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
203                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
204                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
205
206         // IP: 192.168.136.10 -> 128.223.156.35
207         // UDP: 49289 -> 4342
208         // LISP(Type = 3 Map-Register, P=1, M=1
209         // Record Counter: 1
210         // Nonce: 7
211         // Key ID: 0x0000 NO AUTHENTICATION!!
212         // AuthDataLength: 00 Data:
213         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
214         // No-Action
215         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
216         // Priority/Weight: 1/100, Multicast Priority/Weight:
217         // 255/0
218         //
219
220         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
221                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
222                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
223                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
224                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
225                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
226                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
227
228         // IP: 192.168.136.10 -> 128.223.156.35
229         // UDP: 49289 -> 4342
230         // LISP(Type = 3 Map-Register, P=1, M=1
231         // Record Counter: 1
232         // Nonce: 7
233         // Key ID: 0x0000 NO AUTHENTICATION!!
234         // AuthDataLength: 00 Data:
235         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
236         // No-Action
237         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
238         // Priority/Weight: 1/100, Multicast Priority/Weight:
239         // 255/0
240         //
241
242         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
243                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
244                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
245                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
246                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
247                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
248                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
249     }
250
251     @Inject
252     private BundleContext bc;
253     private HttpURLConnection connection;
254
255     // Configure the OSGi container
256     @Configuration
257     public Option[] config() {
258         return options(MappingServiceTestHelper.mappingServiceBundlesWithClusterDAO());
259     }
260
261     @Test
262     public void testSimpleUsage() throws Exception {
263         mapRequestSimple();
264         mapRegisterWithMapNotify();
265         mapRegisterWithMapNotifyAndMapRequest();
266         registerAndQuery__MAC();
267         mapRequestMapRegisterAndMapRequest();
268         mapRegisterWithAuthenticationWithoutConfiguringAKey();
269         mapRegisterWithoutMapNotify();
270     }
271
272     @Test
273     public void testLCAFs() throws Exception {
274         registerAndQuery__SrcDestLCAF();
275         registerAndQuery__KeyValueLCAF();
276         registerAndQuery__ListLCAF();
277         registerAndQuery__ApplicationData();
278         registerAndQuery__TrafficEngineering();
279         registerAndQuery__SegmentLCAF();
280     }
281
282     @Test
283     public void testMask() throws Exception {
284         testPasswordExactMatch();
285         testPasswordMaskMatch();
286         eidPrefixLookupIPv4();
287         eidPrefixLookupIPv6();
288     }
289
290     @Test
291     public void testNorthbound() throws Exception {
292         northboundAddKey();
293         northboundAddMapping();
294         northboundRetrieveKey();
295         northboundRetrieveMapping();
296         northboundRetrieveSourceDestKey();
297         northboundRetrieveSourceDestMapping();
298     }
299
300     @Test
301     public void testOverWriting() throws Exception {
302         testMapRegisterDosntOverwritesOtherSubKeys();
303         testMapRegisterOverwritesSameSubkey();
304         testMapRegisterOverwritesNoSubkey();
305         testMapRegisterDoesntOverwritesNoSubkey();
306     }
307
308     @Test
309     public void testTimeOuts() throws Exception {
310         mapRequestMapRegisterAndMapRequestTestTimeout();
311         mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();
312     }
313
314     // ------------------------------- Simple Tests ---------------------------
315
316     public void mapRequestSimple() throws SocketTimeoutException {
317         cleanUP();
318         sendPacket(mapRequestPacket);
319         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
320         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
321         assertEquals(4435248268955932168L, reply.getNonce().longValue());
322
323     }
324
325     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
326         cleanUP();
327         sendPacket(mapRegisterPacketWithNotify);
328         MapNotify reply = receiveMapNotify();
329         assertEquals(7, reply.getNonce().longValue());
330     }
331
332     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
333         cleanUP();
334         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
335
336         MapReply mapReply = registerAddressAndQuery(eid, 32);
337
338         assertEquals(4, mapReply.getNonce().longValue());
339         assertEquals(LispAFIConvertor.toContainer(locatorEid), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)
340                 .getLispAddressContainer());
341
342     }
343
344     public void registerAndQuery__MAC() throws SocketTimeoutException {
345         cleanUP();
346         String macAddress = "01:02:03:04:05:06";
347
348         MapReply reply = registerAddressAndQuery(asMacAfiAddress(macAddress));
349
350         assertTrue(true);
351         LispAFIAddress addressFromNetwork = LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0).getLispAddressContainer());
352         assertTrue(addressFromNetwork instanceof LispMacAddress);
353         String macAddressFromReply = ((Mac) addressFromNetwork).getMacAddress().getValue();
354
355         assertEquals(macAddress, macAddressFromReply);
356     }
357
358     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
359         cleanUP();
360         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
361         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
362         mapRequestBuilder.setNonce((long) 4);
363         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(
364                 LispAFIConvertor.toContainer(new NoBuilder().setAfi((short) 0).build())).build());
365         mapRequestBuilder.setEidRecord(new ArrayList<EidRecord>());
366         mapRequestBuilder.getEidRecord().add(
367                 new EidRecordBuilder().setMask((short) 32).setLispAddressContainer(LispAFIConvertor.toContainer(eid)).build());
368         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
369         mapRequestBuilder.getItrRloc().add(
370                 new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress))).build());
371         sendMapRequest(mapRequestBuilder.build());
372         MapReply mapReply = receiveMapReply();
373         assertEquals(4, mapReply.getNonce().longValue());
374         assertEquals(0, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
375         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
376         mapRegisterbuilder.setWantMapNotify(true);
377         mapRegisterbuilder.setNonce((long) 8);
378         EidToLocatorRecordBuilder etlrBuilder = new EidToLocatorRecordBuilder();
379         etlrBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(eid));
380         etlrBuilder.setMaskLength((short) 32);
381         etlrBuilder.setRecordTtl(254);
382         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
383         recordBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress("4.3.2.1")));
384         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
385         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
386         mapRegisterbuilder.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
387         mapRegisterbuilder.getEidToLocatorRecord().add(etlrBuilder.build());
388         sendMapRegister(mapRegisterbuilder.build());
389         MapNotify mapNotify = receiveMapNotify();
390         assertEquals(8, mapNotify.getNonce().longValue());
391         sendMapRequest(mapRequestBuilder.build());
392         mapReply = receiveMapReply();
393         assertEquals(4, mapReply.getNonce().longValue());
394         assertEquals(recordBuilder.getLispAddressContainer(), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)
395                 .getLispAddressContainer());
396
397     }
398
399     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
400         cleanUP();
401         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
402         LispAFIAddress rloc1Value = asIPAfiAddress("4.3.2.1");
403         LispAFIAddress rloc1 = LispAFIConvertor.asKeyValue("subkey1", LispAFIConvertor.toPrimitive(rloc1Value));
404         LispAFIAddress rloc2Value = asIPAfiAddress("4.3.2.2");
405         LispAFIAddress rloc2 = LispAFIConvertor.asKeyValue("subkey2", LispAFIConvertor.toPrimitive(rloc2Value));
406         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
407         assertEquals(2, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
408         assertEquals(LispAFIConvertor.toContainer(rloc2), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer());
409         assertEquals(LispAFIConvertor.toContainer(rloc1), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(1).getLispAddressContainer());
410     }
411
412     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
413         cleanUP();
414         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
415         LispAFIAddress rloc1Value = asIPAfiAddress("4.3.2.1");
416         LispAFIAddress rloc1 = LispAFIConvertor.asKeyValue("subkey", LispAFIConvertor.toPrimitive(rloc1Value));
417         LispAFIAddress rloc2Value = asIPAfiAddress("4.3.2.2");
418         LispAFIAddress rloc2 = LispAFIConvertor.asKeyValue("subkey", LispAFIConvertor.toPrimitive(rloc2Value));
419         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
420         assertEquals(1, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
421         assertEquals(LispAFIConvertor.toContainer(rloc2), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer());
422     }
423
424     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
425         cleanUP();
426         lms.setOverwrite(true);
427         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
428         LispAFIAddress rloc1Value = asIPAfiAddress("4.3.2.1");
429         LispAFIAddress rloc2Value = asIPAfiAddress("4.3.2.2");
430         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
431         assertEquals(1, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
432         assertEquals(LispAFIConvertor.toContainer(rloc2Value), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)
433                 .getLispAddressContainer());
434     }
435
436     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
437         cleanUP();
438         lms.setOverwrite(false);
439         LispAFIAddress eid = asIPAfiAddress("1.2.3.4");
440         LispAFIAddress rloc1Value = asIPAfiAddress("4.3.2.1");
441         LispAFIAddress rloc2Value = asIPAfiAddress("4.3.2.2");
442         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
443         assertEquals(2, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
444         LispAddressContainer rloc1ReturnValueContainer = mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer();
445         LispAddressContainer rloc2ReturnValueContainer = mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(1).getLispAddressContainer();
446         assertTrue((LispAFIConvertor.toContainer(rloc1Value).equals(rloc1ReturnValueContainer) && LispAFIConvertor.toContainer(rloc2Value).equals(
447                 rloc2ReturnValueContainer))
448                 || (LispAFIConvertor.toContainer(rloc1Value).equals(rloc2ReturnValueContainer) && LispAFIConvertor.toContainer(rloc2Value).equals(
449                         rloc1ReturnValueContainer)));
450     }
451
452     private MapReply sendMapRegisterTwiceWithDiffrentValues(LispAFIAddress eid, LispAFIAddress rloc1, LispAFIAddress rloc2)
453             throws SocketTimeoutException {
454         MapRegister mb = createMapRegister(eid, rloc1);
455         MapNotify mapNotify = lms.handleMapRegister(mb);
456         MapRequest mr = createMapRequest(eid);
457         MapReply mapReply = lms.handleMapRequest(mr);
458         assertEquals(mb.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer(), mapReply.getEidToLocatorRecord().get(0)
459                 .getLocatorRecord().get(0).getLispAddressContainer());
460         mb = createMapRegister(eid, rloc2);
461         mapNotify = lms.handleMapRegister(mb);
462         assertEquals(8, mapNotify.getNonce().longValue());
463         mr = createMapRequest(eid);
464         sendMapRequest(mr);
465         mapReply = lms.handleMapRequest(mr);
466         return mapReply;
467     }
468
469     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
470         cleanUP();
471         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
472         try {
473             receivePacket(3000);
474             // If didn't timeout then fail:
475             fail();
476         } catch (SocketTimeoutException ste) {
477         }
478     }
479
480     public void mapRegisterWithoutMapNotify() {
481         cleanUP();
482         sendPacket(mapRegisterPacketWithoutNotify);
483         try {
484             receivePacket(3000);
485             // If didn't timeout then fail:
486             fail();
487         } catch (SocketTimeoutException ste) {
488         }
489     }
490
491     // --------------------- Northbound Tests ---------------------------
492
493     private void northboundAddKey() throws Exception {
494         cleanUP();
495         LispIpv4Address address = LispAFIConvertor.asIPAfiAddress("1.2.3.4");
496         int mask = 32;
497         String pass = "asdf";
498
499         URL url = createPutURL("key");
500         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
501         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
502
503         String retrievedKey = lms.getAuthenticationKey(LispAFIConvertor.toContainer(address), mask);
504
505         // Check stored password matches the one sent
506         assertEquals(pass, retrievedKey);
507
508     }
509
510     private void northboundRetrieveSourceDestKey() throws Exception {
511         cleanUP();
512         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 address1 = (org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4) LispAFIConvertor
513                 .toPrimitive(LispAFIConvertor.asIPAfiAddress("10.0.0.1"));
514         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 address2 = (org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4) LispAFIConvertor
515                 .toPrimitive(LispAFIConvertor.asIPAfiAddress("10.0.0.2"));
516         int mask1 = 32;
517         int mask2 = 32;
518         LcafSourceDest sourceDestAddress = new LcafSourceDestBuilder().setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode())
519                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
520                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build()).setSrcMaskLength((short) mask1)
521                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build()).setDstMaskLength((short) mask2).build();
522         String pass = "asdf";
523
524         lms.addAuthenticationKey(LispAFIConvertor.toContainer(sourceDestAddress), mask1, pass);
525
526         // URL url = createGetKeyIPv4URL(address1, mask1);
527         URL url = createGetKeySourceDestURL(address1.getAfi(), ((LispIpv4Address) sourceDestAddress.getSrcAddress().getPrimitiveAddress())
528                 .getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(), ((LispIpv4Address) sourceDestAddress.getDstAddress()
529                 .getPrimitiveAddress()).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
530         String reply = callURL("GET", null, "application/json", null, url);
531         JSONTokener jt = new JSONTokener(reply);
532         JSONObject json = new JSONObject(jt);
533
534         // test that the password matches what was we expected.
535         assertEquals(pass, json.get("key"));
536
537     }
538
539     private void northboundRetrieveKey() throws Exception {
540         cleanUP();
541         LispIpv4Address address = LispAFIConvertor.asIPAfiAddress("10.0.0.1");
542         int mask = 32;
543         String pass = "asdf";
544
545         lms.addAuthenticationKey(LispAFIConvertor.toContainer(address), mask, pass);
546
547         URL url = createGetKeyIPv4URL(address, mask);
548         String reply = callURL("GET", null, "application/json", null, url);
549         JSONTokener jt = new JSONTokener(reply);
550         JSONObject json = new JSONObject(jt);
551
552         // test that the password matches what was we expected.
553         assertEquals(pass, json.get("key"));
554
555     }
556
557     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
558         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
559                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
560     }
561
562     private void northboundAddMapping() throws Exception {
563         cleanUP();
564         String pass = "asdf";
565         LispIpv4Address eid = LispAFIConvertor.asIPAfiAddress("10.0.0.1");
566         int mask = 32;
567         LispIpv4Address rloc = LispAFIConvertor.asIPAfiAddress("20.0.0.2");
568
569         // NB add mapping always checks the key
570         lms.addAuthenticationKey(LispAFIConvertor.toContainer(eid), mask, pass);
571
572         URL url = createPutURL("mapping");
573         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
574         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
575
576         // Retrieve the RLOC from the database
577         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
578         mapRequestBuilder.setPitr(false);
579         mapRequestBuilder.setEidRecord(new ArrayList<EidRecord>());
580         mapRequestBuilder.getEidRecord().add(
581                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(LispAFIConvertor.toContainer(eid)).build());
582         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
583
584         LispIpv4Address retrievedRloc = (LispIpv4Address) mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer()
585                 .getAddress();
586
587         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
588
589     }
590
591     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
592         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ " + "\"proxyMapReply\" : false, "
593                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : " + "{ " + "\"ipAddress\" : \""
594                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "}," + "\"mapVersion\" : 0,"
595                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ " + "\"multicastPriority\" : 1,"
596                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\"," + "\"afi\" : "
597                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50," + "\"rlocProbed\" : false, "
598                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], " + "\"recordTtl\" : 100" + "} " + "], "
599                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
600
601         return jsonString;
602     }
603
604     private void northboundRetrieveMapping() throws Exception {
605         cleanUP();
606         LispIpv4Address eid = LispAFIConvertor.asIPAfiAddress("10.0.0.1");
607         int mask = 32;
608         LispIpv4Address rloc = LispAFIConvertor.asIPAfiAddress("20.0.0.2");
609         // Insert mapping in the database
610         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
611         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
612         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(eid));
613         etlr.setMaskLength((short) mask);
614         etlr.setRecordTtl(254);
615         etlr.setAuthoritative(false);
616         etlr.setAction(Action.NoAction);
617         LocatorRecordBuilder record = new LocatorRecordBuilder();
618         record.setLispAddressContainer(LispAFIConvertor.toContainer(rloc));
619         record.setRouted(true);
620         record.setRlocProbed(false);
621         record.setLocalLocator(false);
622         record.setPriority((short) 1);
623         record.setWeight((short) 50);
624         record.setMulticastPriority((short) 1);
625         record.setMulticastWeight((short) 1);
626         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
627         etlr.getLocatorRecord().add(record.build());
628         mapRegister.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
629         mapRegister.getEidToLocatorRecord().add(etlr.build());
630         lms.handleMapRegister(mapRegister.build());
631
632         // Get mapping using NB interface. No IID used
633         URL url = createGetMappingIPv4URL(0, eid, mask);
634         String reply = callURL("GET", null, "application/json", null, url);
635         JSONTokener jt = new JSONTokener(reply);
636         JSONObject json = new JSONObject(jt);
637
638         // With just one locator, locators is not a JSONArray
639         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric").getString("ipAddress");
640
641         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
642
643     }
644
645     private void northboundRetrieveSourceDestMapping() throws Exception {
646         cleanUP();
647         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 address1 = (org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4) LispAFIConvertor
648                 .toPrimitive(LispAFIConvertor.asIPAfiAddress("10.0.0.1"));
649         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 address2 = (org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4) LispAFIConvertor
650                 .toPrimitive(LispAFIConvertor.asIPAfiAddress("10.0.0.2"));
651         int mask1 = 32;
652         int mask2 = 32;
653         LcafSourceDest sourceDestAddress = new LcafSourceDestBuilder().setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode())
654                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
655                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build()).setSrcMaskLength((short) mask1)
656                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build()).setDstMaskLength((short) mask2).build();
657         LispIpv4Address rloc = LispAFIConvertor.asIPAfiAddress("20.0.0.2");
658
659         // Insert mapping in the database
660         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
661         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
662         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(sourceDestAddress));
663         etlr.setMaskLength((short) mask1);
664         etlr.setRecordTtl(254);
665         etlr.setAuthoritative(false);
666         etlr.setAction(Action.NoAction);
667         LocatorRecordBuilder record = new LocatorRecordBuilder();
668         record.setLispAddressContainer(LispAFIConvertor.toContainer(rloc));
669         record.setRouted(true);
670         record.setRlocProbed(false);
671         record.setLocalLocator(false);
672         record.setPriority((short) 1);
673         record.setWeight((short) 50);
674         record.setMulticastPriority((short) 1);
675         record.setMulticastWeight((short) 1);
676         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
677         etlr.getLocatorRecord().add(record.build());
678         mapRegister.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
679         mapRegister.getEidToLocatorRecord().add(etlr.build());
680         lms.handleMapRegister(mapRegister.build());
681
682         // Get mapping using NB interface. No IID used
683         URL url = createGetMappingSourceDestURL(address1.getAfi(), address1.getIpv4Address().getValue(), mask1, address2.getIpv4Address().getValue(),
684                 mask2);
685         String reply = callURL("GET", null, "application/json", null, url);
686         JSONTokener jt = new JSONTokener(reply);
687         JSONObject json = new JSONObject(jt);
688
689         // With just one locator, locators is not a JSONArray
690         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric").getString("ipAddress");
691
692         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
693
694     }
695
696     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
697         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key", address.getAfi().shortValue(),
698                 address.getIpv4Address().getValue(), mask);
699         URL url = new URL(restUrl);
700         return url;
701     }
702
703     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask) throws MalformedURLException {
704         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d", "key", afi, srcAddress, srcMask,
705                 dstAddress, dstMask);
706         URL url = new URL(restUrl);
707         return url;
708     }
709
710     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask) throws MalformedURLException {
711         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d", "mapping", afi, srcAddress,
712                 srcMask, dstAddress, dstMask);
713         URL url = new URL(restUrl);
714         return url;
715     }
716
717     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
718         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping", iid, address.getAfi()
719                 .shortValue(), address.getIpv4Address().getValue(), mask);
720         URL url = new URL(restUrl);
721         return url;
722     }
723
724     private URL createPutURL(String resource) throws MalformedURLException {
725
726         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
727
728         URL url = new URL(restUrl);
729         return url;
730     }
731
732     private String createAuthenticationString() {
733         String authString = "admin:admin";
734         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
735         String authStringEnc = new String(authEncBytes);
736         return authStringEnc;
737     }
738
739     private String callURL(String method, String content, String accept, String body, URL url) throws IOException, JSONException {
740         String authStringEnc = createAuthenticationString();
741         connection = (HttpURLConnection) url.openConnection();
742         connection.setRequestMethod(method);
743         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
744         if (content != null) {
745             connection.setRequestProperty("Content-Type", content);
746         }
747         if (accept != null) {
748             connection.setRequestProperty("Accept", accept);
749         }
750         if (body != null) {
751             // now add the request body
752             connection.setDoOutput(true);
753             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
754             wr.write(body);
755             wr.flush();
756         }
757         connection.connect();
758
759         // getting the result, first check response code
760         Integer httpResponseCode = connection.getResponseCode();
761
762         if (httpResponseCode > 299) {
763             logger.trace("HTTP Address: " + url);
764             logger.trace("HTTP Response Code: " + httpResponseCode);
765             fail();
766         }
767
768         InputStream is = connection.getInputStream();
769         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
770         StringBuilder sb = new StringBuilder();
771         int cp;
772         while ((cp = rd.read()) != -1) {
773             sb.append((char) cp);
774         }
775         is.close();
776         connection.disconnect();
777         return (sb.toString());
778     }
779
780     // timePeriod - in ms
781     public void assertNoPacketReceived(int timePeriod) {
782         try {
783             receivePacket(timePeriod);
784             // If didn't timeout then fail:
785             fail();
786         } catch (SocketTimeoutException ste) {
787         }
788     }
789
790     // ------------------------------- Mask Tests ---------------------------
791
792     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
793         cleanUP();
794         runPrefixTest(LispAFIConvertor.asIPAfiAddress("1.2.3.4"), 16, LispAFIConvertor.asIPAfiAddress("1.2.3.2"),
795                 LispAFIConvertor.asIPAfiAddress("1.1.1.1"), (byte) 32);
796     }
797
798     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
799         cleanUP();
800         runPrefixTest(LispAFIConvertor.asIPv6AfiAddress("1:2:3:4:5:6:7:8"), 64, LispAFIConvertor.asIPv6AfiAddress("1:2:3:4:5:1:2:3"),
801                 LispAFIConvertor.asIPv6AfiAddress("1:2:3:1:2:3:1:2"), 128);
802     }
803
804     private void runPrefixTest(LispAFIAddress registerEID, int registerdMask, LispAFIAddress matchedAddress, LispAFIAddress unMatchedAddress, int mask)
805             throws SocketTimeoutException {
806
807         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
808         mapRegister.setWantMapNotify(true);
809         mapRegister.setNonce((long) 8);
810         mapRegister.setWantMapNotify(true);
811         mapRegister.setKeyId((short) 0);
812         mapRegister.setAuthenticationData(new byte[0]);
813         mapRegister.setNonce((long) 8);
814         mapRegister.setProxyMapReply(false);
815         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
816         etlr.setRecordTtl(254);
817         etlr.setAction(Action.NoAction);
818         etlr.setAuthoritative(false);
819         etlr.setMapVersion((short) 0);
820         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(registerEID));
821         etlr.setMaskLength((short) registerdMask);
822         etlr.setRecordTtl(254);
823         LocatorRecordBuilder record = new LocatorRecordBuilder();
824         record.setLispAddressContainer(LispAFIConvertor.toContainer(LispAFIConvertor.asIPAfiAddress("4.3.2.1")));
825         record.setLocalLocator(false);
826         record.setRlocProbed(false);
827         record.setRouted(true);
828         record.setMulticastPriority((short) 0);
829         record.setMulticastWeight((short) 0);
830         record.setPriority((short) 0);
831         record.setWeight((short) 0);
832         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
833         etlr.getLocatorRecord().add(record.build());
834         mapRegister.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
835         mapRegister.getEidToLocatorRecord().add(etlr.build());
836         sendMapRegister(mapRegister.build());
837         MapNotify mapNotify = receiveMapNotify();
838         assertEquals(8, mapNotify.getNonce().longValue());
839         MapRequestBuilder mapRequest = new MapRequestBuilder();
840         mapRequest.setNonce((long) 4);
841         mapRequest.setSourceEid(new SourceEidBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress))).build());
842         mapRequest.setEidRecord(new ArrayList<EidRecord>());
843         mapRequest.setAuthoritative(false);
844         mapRequest.setMapDataPresent(false);
845         mapRequest.setPitr(false);
846         mapRequest.setProbe(false);
847         mapRequest.setSmr(false);
848         mapRequest.setSmrInvoked(false);
849         mapRequest.getEidRecord().add(
850                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(LispAFIConvertor.toContainer(matchedAddress)).build());
851         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
852         mapRequest.getItrRloc().add(
853                 new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(LispAFIConvertor.asIPAfiAddress(ourAddress))).build());
854         sendMapRequest(mapRequest.build());
855         MapReply mapReply = receiveMapReply();
856         assertEquals(4, mapReply.getNonce().longValue());
857         assertEquals(record.getLispAddressContainer(), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0).getLispAddressContainer());
858         mapRequest.setEidRecord(new ArrayList<EidRecord>());
859         mapRequest.getEidRecord().add(
860                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(LispAFIConvertor.toContainer(unMatchedAddress)).build());
861         sendMapRequest(mapRequest.build());
862         mapReply = receiveMapReply();
863         assertEquals(0, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
864     }
865
866     // This registers an IP with a MapRegister, then adds a password via the
867     // northbound REST API
868     // and checks that the password works
869     public void testPasswordExactMatch() throws Exception {
870         cleanUP();
871         String ipString = "10.0.0.1";
872         LispIpv4Address address = LispAFIConvertor.asIPAfiAddress(ipString);
873         int mask = 32;
874         String pass = "pass";
875
876         URL url = createPutURL("key");
877
878         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
879
880         logger.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
881         logger.trace("Address: " + address);
882
883         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232, (byte) 31, (byte) 249, (byte) 87,
884                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53, (byte) 196, (byte) 62 };
885
886         byte[] zeros = new byte[20];
887
888         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
889
890         // build a MapRegister
891         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
892         mapRegister.setWantMapNotify(true);
893         mapRegister.setNonce((long) 8);
894         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
895         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(address));
896         etlr.setMaskLength((short) mask);
897         etlr.setRecordTtl(254);
898         LocatorRecordBuilder record = new LocatorRecordBuilder();
899         record.setLispAddressContainer(LispAFIConvertor.toContainer(locatorEid));
900         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
901         etlr.getLocatorRecord().add(record.build());
902         mapRegister.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
903         mapRegister.getEidToLocatorRecord().add(etlr.build());
904
905         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
906         mapRegister.setAuthenticationData(zeros);
907
908         sendMapRegister(mapRegister.build());
909         assertNoPacketReceived(3000);
910
911         mapRegister.setAuthenticationData(expectedSha);
912
913         sendMapRegister(mapRegister.build());
914
915         assertMapNotifyRecieved();
916     }
917
918     public void testPasswordMaskMatch() throws Exception {
919         cleanUP();
920         LispIpv4Address addressInRange = LispAFIConvertor.asIPAfiAddress("10.20.30.40");
921         LispIpv4Address addressOutOfRange = LispAFIConvertor.asIPAfiAddress("20.40.30.40");
922         LispIpv4Address range = LispAFIConvertor.asIPAfiAddress("10.20.30.0");
923
924         int mask = 32;
925         String pass = "pass";
926
927         URL url = createPutURL("key");
928         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
929
930         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
931         // build a MapRegister
932         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
933
934         mapRegister.setWantMapNotify(true);
935         mapRegister.setNonce((long) 8);
936         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
937         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(addressInRange));
938         etlr.setMaskLength((short) mask);
939         etlr.setRecordTtl(254);
940         LocatorRecordBuilder record = new LocatorRecordBuilder();
941         record.setLispAddressContainer(LispAFIConvertor.toContainer(locatorEid));
942         record.setLispAddressContainer(LispAFIConvertor.toContainer(locatorEid));
943         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
944         etlr.getLocatorRecord().add(record.build());
945         mapRegister.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
946         mapRegister.getEidToLocatorRecord().add(etlr.build());
947
948         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
949         mapRegister
950                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4, -67, -113, 104, -110, -71 });
951
952         sendMapRegister(mapRegister.build());
953
954         assertMapNotifyRecieved();
955
956         etlr.setLispAddressContainer(LispAFIConvertor.toContainer(addressOutOfRange));
957         mapRegister
958                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123, -71, -14, -99, 67, -23, -73 });
959
960         sendMapRegister(mapRegister.build());
961         assertNoPacketReceived(3000);
962     }
963
964     private MapReply registerAddressAndQuery(LispAFIAddress eid) throws SocketTimeoutException {
965         return registerAddressAndQuery(eid, -1);
966     }
967
968     // takes an address, packs it in a MapRegister, sends it, returns the
969     // MapReply
970     private MapReply registerAddressAndQuery(LispAFIAddress eid, int maskLength) throws SocketTimeoutException {
971         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
972         mapRegisterBuilder.setWantMapNotify(true);
973         mapRegisterBuilder.setKeyId((short) 0);
974         mapRegisterBuilder.setAuthenticationData(new byte[0]);
975         mapRegisterBuilder.setNonce((long) 8);
976         mapRegisterBuilder.setProxyMapReply(false);
977         EidToLocatorRecordBuilder etlrBuilder = new EidToLocatorRecordBuilder();
978         etlrBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(eid));
979         if (maskLength != -1) {
980             etlrBuilder.setMaskLength((short) maskLength);
981         } else {
982             etlrBuilder.setMaskLength((short) 0);
983         }
984         etlrBuilder.setRecordTtl(254);
985         etlrBuilder.setAction(Action.NoAction);
986         etlrBuilder.setAuthoritative(false);
987         etlrBuilder.setMapVersion((short) 0);
988         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
989         recordBuilder.setLocalLocator(false);
990         recordBuilder.setRlocProbed(false);
991         recordBuilder.setRouted(true);
992         recordBuilder.setMulticastPriority((short) 0);
993         recordBuilder.setMulticastWeight((short) 0);
994         recordBuilder.setPriority((short) 0);
995         recordBuilder.setWeight((short) 0);
996         recordBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(locatorEid));
997         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
998         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
999         mapRegisterBuilder.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
1000         mapRegisterBuilder.getEidToLocatorRecord().add(etlrBuilder.build());
1001         sendMapRegister(mapRegisterBuilder.build());
1002         MapNotify mapNotify = receiveMapNotify();
1003         assertEquals(8, mapNotify.getNonce().longValue());
1004         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1005         mapRequestBuilder.setNonce((long) 4);
1006         mapRequestBuilder.setEidRecord(new ArrayList<EidRecord>());
1007         mapRequestBuilder.getEidRecord().add(
1008                 new EidRecordBuilder().setMask((short) 32).setLispAddressContainer(LispAFIConvertor.toContainer(eid)).build());
1009         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1010         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress)))
1011                 .build());
1012         mapRequestBuilder.getItrRloc().add(
1013                 new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress))).build());
1014         mapRequestBuilder.setAuthoritative(false);
1015         mapRequestBuilder.setMapDataPresent(false);
1016         mapRequestBuilder.setPitr(false);
1017         mapRequestBuilder.setProbe(false);
1018         mapRequestBuilder.setSmr(false);
1019         mapRequestBuilder.setSmrInvoked(false);
1020         sendMapRequest(mapRequestBuilder.build());
1021         return receiveMapReply();
1022     }
1023
1024     // ------------------------------- LCAF Tests ---------------------------
1025
1026     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1027         cleanUP();
1028         String ipString = "10.20.30.200";
1029         String macString = "01:02:03:04:05:06";
1030         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 addrToSend1 = asPrimitiveIPAfiAddress(ipString);
1031         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Mac addrToSend2 = asPrimitiveMacAfiAddress(macString);
1032         LcafSourceDestBuilder builder = new LcafSourceDestBuilder();
1033         builder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode());
1034         builder.setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode());
1035         builder.setSrcMaskLength((short) 0);
1036         builder.setDstMaskLength((short) 0);
1037         builder.setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(addrToSend1).build());
1038         builder.setDstAddress(new DstAddressBuilder().setPrimitiveAddress(addrToSend2).build());
1039
1040         MapReply reply = registerAddressAndQuery(builder.build());
1041
1042         LispAddressContainer fromNetwork = reply.getEidToLocatorRecord().get(0).getLispAddressContainer();
1043         assertTrue(fromNetwork.getAddress() instanceof LcafSourceDestAddress);
1044         LcafSourceDestAddress sourceDestFromNetwork = (LcafSourceDestAddress) fromNetwork.getAddress();
1045
1046         LispAFIAddress receivedAddr1 = (LispAFIAddress) sourceDestFromNetwork.getSrcAddress().getPrimitiveAddress();
1047         LispAFIAddress receivedAddr2 = (LispAFIAddress) sourceDestFromNetwork.getDstAddress().getPrimitiveAddress();
1048
1049         assertTrue(receivedAddr1 instanceof LispIpv4Address);
1050         assertTrue(receivedAddr2 instanceof LispMacAddress);
1051
1052         LispIpv4Address receivedIP = (LispIpv4Address) receivedAddr1;
1053         LispMacAddress receivedMAC = (LispMacAddress) receivedAddr2;
1054
1055         assertEquals(ipString, receivedIP.getIpv4Address().getValue());
1056         assertEquals(macString, receivedMAC.getMacAddress().getValue());
1057     }
1058
1059     @Test
1060     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1061         cleanUP();
1062         String ipString = "10.20.30.200";
1063         String macString = "01:02:03:04:05:06";
1064         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 addrToSend1 = asPrimitiveIPAfiAddress(ipString);
1065         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Mac addrToSend2 = asPrimitiveMacAfiAddress(macString);
1066         LcafKeyValueBuilder builder = new LcafKeyValueBuilder();
1067         builder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode());
1068         builder.setLcafType((short) LispCanonicalAddressFormatEnum.KEY_VALUE.getLispCode());
1069         builder.setKey(new KeyBuilder().setPrimitiveAddress(addrToSend1).build());
1070         builder.setValue(new ValueBuilder().setPrimitiveAddress(addrToSend2).build());
1071
1072         MapReply reply = registerAddressAndQuery(builder.build());
1073
1074         LispAddressContainer fromNetwork = reply.getEidToLocatorRecord().get(0).getLispAddressContainer();
1075         assertTrue(fromNetwork.getAddress() instanceof LcafKeyValueAddress);
1076         LcafKeyValueAddress keyValueFromNetwork = (LcafKeyValueAddress) fromNetwork.getAddress();
1077
1078         LispAFIAddress receivedAddr1 = (LispAFIAddress) keyValueFromNetwork.getKey().getPrimitiveAddress();
1079         LispAFIAddress receivedAddr2 = (LispAFIAddress) keyValueFromNetwork.getValue().getPrimitiveAddress();
1080
1081         assertTrue(receivedAddr1 instanceof LispIpv4Address);
1082         assertTrue(receivedAddr2 instanceof LispMacAddress);
1083
1084         LispIpv4Address receivedIP = (LispIpv4Address) receivedAddr1;
1085         LispMacAddress receivedMAC = (LispMacAddress) receivedAddr2;
1086
1087         assertEquals(ipString, receivedIP.getIpv4Address().getValue());
1088         assertEquals(macString, receivedMAC.getMacAddress().getValue());
1089     }
1090
1091     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1092         cleanUP();
1093         String macString = "01:02:03:04:05:06";
1094         String ipString = "10.20.255.30";
1095         LcafListBuilder listbuilder = new LcafListBuilder();
1096         listbuilder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode()).setLcafType((short) LispCanonicalAddressFormatEnum.LIST.getLispCode());
1097         listbuilder.setAddresses(new ArrayList<Addresses>());
1098         listbuilder.getAddresses().add(new AddressesBuilder().setPrimitiveAddress(LispAFIConvertor.toPrimitive(asIPAfiAddress(ipString))).build());
1099         listbuilder.getAddresses().add(new AddressesBuilder().setPrimitiveAddress(LispAFIConvertor.toPrimitive(asMacAfiAddress(macString))).build());
1100
1101         MapReply reply = registerAddressAndQuery(listbuilder.build());
1102
1103         LispAFIAddress receivedAddress = LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0).getLispAddressContainer());
1104
1105         assertTrue(receivedAddress instanceof LcafListAddress);
1106
1107         LcafListAddress listAddrFromNetwork = (LcafListAddress) receivedAddress;
1108         LispAFIAddress receivedAddr1 = (LispAFIAddress) listAddrFromNetwork.getAddresses().get(0).getPrimitiveAddress();
1109         LispAFIAddress receivedAddr2 = (LispAFIAddress) listAddrFromNetwork.getAddresses().get(1).getPrimitiveAddress();
1110
1111         assertTrue(receivedAddr1 instanceof LispIpv4Address);
1112         assertTrue(receivedAddr2 instanceof LispMacAddress);
1113
1114         assertEquals(macString, ((LispMacAddress) receivedAddr2).getMacAddress().getValue());
1115         assertEquals(ipString, ((LispIpv4Address) receivedAddr1).getIpv4Address().getValue());
1116     }
1117
1118     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
1119         cleanUP();
1120         String ipString = "10.20.255.30";
1121         int instanceId = 6;
1122         LcafSegmentBuilder builder = new LcafSegmentBuilder();
1123         builder.setInstanceId((long) instanceId);
1124         builder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode()).setLcafType((short) LispCanonicalAddressFormatEnum.SEGMENT.getLispCode());
1125         builder.setAddress(new AddressBuilder().setPrimitiveAddress(LispAFIConvertor.toPrimitive(asIPAfiAddress(ipString))).build());
1126
1127         MapReply reply = registerAddressAndQuery(builder.build());
1128
1129         LispAFIAddress receivedAddress = LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0).getLispAddressContainer());
1130         assertTrue(receivedAddress instanceof LcafSegmentAddress);
1131
1132         LcafSegmentAddress segmentfromNetwork = (LcafSegmentAddress) receivedAddress;
1133         LispAFIAddress addrFromSegment = (LispAFIAddress) segmentfromNetwork.getAddress().getPrimitiveAddress();
1134         assertTrue(addrFromSegment instanceof LispIpv4Address);
1135         assertEquals(ipString, ((LispIpv4Address) addrFromSegment).getIpv4Address().getValue());
1136
1137         assertEquals(instanceId, segmentfromNetwork.getInstanceId().intValue());
1138     }
1139
1140     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
1141         cleanUP();
1142         String macString = "01:02:03:04:05:06";
1143         String ipString = "10.20.255.30";
1144         HopBuilder hopBuilder = new HopBuilder();
1145         hopBuilder.setPrimitiveAddress(LispAFIConvertor.toPrimitive(asIPAfiAddress(ipString)));
1146         Hop hop1 = hopBuilder.build();
1147         hopBuilder.setPrimitiveAddress(LispAFIConvertor.toPrimitive(asMacAfiAddress(macString)));
1148         Hop hop2 = hopBuilder.build();
1149         HopsBuilder hb = new HopsBuilder();
1150         hb.setHop(hop1);
1151         hb.setLookup(true);
1152         hb.setRLOCProbe(false);
1153         hb.setStrict(true);
1154         HopsBuilder hb2 = new HopsBuilder();
1155         hb2.setHop(hop2);
1156         hb2.setLookup(false);
1157         hb2.setRLOCProbe(true);
1158         hb2.setStrict(false);
1159         Hops hops1 = hb.build();
1160         Hops hops2 = hb2.build();
1161         LcafTrafficEngineeringBuilder trafficBuilder = new LcafTrafficEngineeringBuilder();
1162         trafficBuilder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode()).setLcafType(
1163                 (short) LispCanonicalAddressFormatEnum.TRAFFIC_ENGINEERING.getLispCode());
1164         trafficBuilder.setHops(new ArrayList<Hops>());
1165         trafficBuilder.getHops().add(hb.build());
1166         trafficBuilder.getHops().add(hb2.build());
1167
1168         MapReply reply = registerAddressAndQuery(trafficBuilder.build());
1169
1170         assertTrue(LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0).getLispAddressContainer()) instanceof LcafTrafficEngineeringAddress);
1171
1172         LcafTrafficEngineeringAddress receivedAddress = (LcafTrafficEngineeringAddress) LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0)
1173                 .getLispAddressContainer());
1174
1175         ReencapHop receivedHop1 = receivedAddress.getHops().get(0);
1176         ReencapHop receivedHop2 = receivedAddress.getHops().get(1);
1177
1178         assertEquals(true, hops1.isLookup());
1179         assertEquals(false, hops1.isRLOCProbe());
1180         assertEquals(true, hops1.isStrict());
1181
1182         assertEquals(false, hops2.isLookup());
1183         assertEquals(true, hops2.isRLOCProbe());
1184         assertEquals(false, hops2.isStrict());
1185
1186         assertTrue(receivedHop1.getHop().getPrimitiveAddress() instanceof LispIpv4Address);
1187         assertTrue(receivedHop2.getHop().getPrimitiveAddress() instanceof LispMacAddress);
1188
1189         assertEquals(ipString, ((LispIpv4Address) receivedHop1.getHop().getPrimitiveAddress()).getIpv4Address().getValue());
1190         assertEquals(macString, ((LispMacAddress) receivedHop2.getHop().getPrimitiveAddress()).getMacAddress().getValue());
1191     }
1192
1193     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
1194         cleanUP();
1195         String ipString = "1.2.3.4";
1196         short protocol = 1;
1197         int ipTOs = 2;
1198         int localPort = 3;
1199         int remotePort = 4;
1200
1201         LcafApplicationDataBuilder builder = new LcafApplicationDataBuilder();
1202         builder.setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode()).setLcafType((short) LispCanonicalAddressFormatEnum.APPLICATION_DATA.getLispCode());
1203         builder.setIpTos(ipTOs);
1204         builder.setProtocol(protocol);
1205         builder.setLocalPort(new PortNumber(localPort));
1206         builder.setRemotePort(new PortNumber(remotePort));
1207         builder.setAddress(new org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lcafapplicationdataaddress.AddressBuilder()
1208                 .setPrimitiveAddress(LispAFIConvertor.toPrimitive(asIPAfiAddress(ipString))).build());
1209
1210         LcafApplicationDataAddress addressToSend = builder.build();
1211
1212         MapReply reply = registerAddressAndQuery(addressToSend);
1213
1214         LispAFIAddress receivedAddress = LispAFIConvertor.toAFI(reply.getEidToLocatorRecord().get(0).getLispAddressContainer());
1215
1216         assertTrue(receivedAddress instanceof LcafApplicationDataAddress);
1217
1218         LcafApplicationDataAddress receivedApplicationDataAddress = (LcafApplicationDataAddress) receivedAddress;
1219         assertEquals(protocol, receivedApplicationDataAddress.getProtocol().intValue());
1220         assertEquals(ipTOs, receivedApplicationDataAddress.getIpTos().intValue());
1221         assertEquals(localPort, receivedApplicationDataAddress.getLocalPort().getValue().intValue());
1222         assertEquals(remotePort, receivedApplicationDataAddress.getRemotePort().getValue().intValue());
1223
1224         LispIpv4Address ipAddressReceived = (LispIpv4Address) receivedApplicationDataAddress.getAddress().getPrimitiveAddress();
1225         assertEquals(ipString, ipAddressReceived.getIpv4Address().getValue());
1226     }
1227
1228     // ------------------- TimeOut Tests -----------
1229
1230     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
1231         cleanUP();
1232         LispIpv4Address eid = LispAFIConvertor.asIPAfiAddress("1.2.3.4");
1233         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1234         mapRequestBuilder.setNonce((long) 4);
1235         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(
1236                 LispAFIConvertor.toContainer(new NoBuilder().setAfi((short) 0).build())).build());
1237         mapRequestBuilder.setEidRecord(new ArrayList<EidRecord>());
1238         mapRequestBuilder.getEidRecord().add(
1239                 new EidRecordBuilder().setMask((short) 32).setLispAddressContainer(LispAFIConvertor.toContainer(eid)).build());
1240         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1241         mapRequestBuilder.getItrRloc().add(
1242                 new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress))).build());
1243         sendMapRequest(mapRequestBuilder.build());
1244         MapReply mapReply = receiveMapReply();
1245         assertEquals(4, mapReply.getNonce().longValue());
1246         assertEquals(0, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
1247         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1248         mapRegisterbuilder.setWantMapNotify(true);
1249         mapRegisterbuilder.setNonce((long) 8);
1250         EidToLocatorRecordBuilder etlrBuilder = new EidToLocatorRecordBuilder();
1251         etlrBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(eid));
1252         etlrBuilder.setMaskLength((short) 32);
1253         etlrBuilder.setRecordTtl(254);
1254         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1255         recordBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress("4.3.2.1")));
1256         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1257         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1258         mapRegisterbuilder.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
1259         mapRegisterbuilder.getEidToLocatorRecord().add(etlrBuilder.build());
1260         sendMapRegister(mapRegisterbuilder.build());
1261         MapNotify mapNotify = receiveMapNotify();
1262         assertEquals(8, mapNotify.getNonce().longValue());
1263         sendMapRequest(mapRequestBuilder.build());
1264         mapReply = receiveMapReply();
1265         assertEquals(4, mapReply.getNonce().longValue());
1266         assertEquals(recordBuilder.getLispAddressContainer(), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)
1267                 .getLispAddressContainer());
1268         causeEntryToBeCleaned();
1269         sendMapRequest(mapRequestBuilder.build());
1270         mapReply = receiveMapReply();
1271         assertEquals(0, mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().size());
1272     }
1273
1274     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
1275         cleanUP();
1276         LispIpv4Address eid = LispAFIConvertor.asIPAfiAddress("1.2.3.4");
1277         MapRequest mapRequest = createMapRequest(eid);
1278
1279         testTTLBeforeRegister(mapRequest);
1280
1281         registerForTTL(eid);
1282
1283         testTTLAfterRegister(mapRequest);
1284
1285         causeEntryToBeCleaned();
1286         testTTLAfterClean(mapRequest);
1287
1288         northboundAddKey();
1289         testTTLAfterAutherize(mapRequest);
1290
1291     }
1292
1293     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
1294         MapReply mapReply;
1295         sendMapRequest(mapRequest);
1296         mapReply = receiveMapReply();
1297         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1298     }
1299
1300     private void causeEntryToBeCleaned() {
1301         clusterService.setTimeUnit(TimeUnit.NANOSECONDS);
1302         clusterService.cleanOld();
1303     }
1304
1305     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
1306         MapReply mapReply;
1307         sendMapRequest(mapRequest);
1308         mapReply = receiveMapReply();
1309         assertEquals(LispAFIConvertor.toContainer(asIPAfiAddress("4.3.2.1")), mapReply.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)
1310                 .getLispAddressContainer());
1311         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
1312     }
1313
1314     private void registerForTTL(LispIpv4Address eid) throws SocketTimeoutException {
1315         MapRegister mapRegister = createMapRegister(eid);
1316         sendMapRegister(mapRegister);
1317         assertMapNotifyRecieved();
1318     }
1319
1320     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
1321         MapReply mapReply;
1322         sendMapRequest(mapRequest);
1323         mapReply = receiveMapReply();
1324         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1325     }
1326
1327     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
1328         MapReply mapReply;
1329         sendMapRequest(mapRequest);
1330         mapReply = receiveMapReply();
1331         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
1332     }
1333
1334     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
1335         assertEquals(expectedTTL, mapReply.getEidToLocatorRecord().get(0).getRecordTtl().intValue());
1336         assertEquals(expectedAction, mapReply.getEidToLocatorRecord().get(0).getAction());
1337     }
1338
1339     private MapRegister createMapRegister(LispAFIAddress eid, LispAFIAddress rloc) {
1340         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1341         mapRegisterbuilder.setWantMapNotify(true);
1342         mapRegisterbuilder.setNonce((long) 8);
1343         mapRegisterbuilder.setKeyId((short) 0);
1344         EidToLocatorRecordBuilder etlrBuilder = new EidToLocatorRecordBuilder();
1345         etlrBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(eid));
1346         etlrBuilder.setMaskLength((short) 24);
1347         etlrBuilder.setRecordTtl(254);
1348         etlrBuilder.setAuthoritative(false);
1349         etlrBuilder.setAction(Action.NoAction);
1350         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1351         recordBuilder.setLispAddressContainer(LispAFIConvertor.toContainer(rloc));
1352         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1353         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1354         mapRegisterbuilder.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
1355         mapRegisterbuilder.getEidToLocatorRecord().add(etlrBuilder.build());
1356         MapRegister mapRegister = mapRegisterbuilder.build();
1357         return mapRegister;
1358     }
1359
1360     private MapRegister createMapRegister(LispIpv4Address eid) {
1361         return createMapRegister(eid, asIPAfiAddress("4.3.2.1"));
1362     }
1363
1364     private MapRequest createMapRequest(LispAFIAddress eid) {
1365         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1366         mapRequestBuilder.setNonce((long) 4);
1367         mapRequestBuilder.setPitr(false);
1368         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(
1369                 LispAFIConvertor.toContainer(new NoBuilder().setAfi((short) 0).build())).build());
1370         mapRequestBuilder.setEidRecord(new ArrayList<EidRecord>());
1371         mapRequestBuilder.getEidRecord().add(
1372                 new EidRecordBuilder().setMask((short) 32).setLispAddressContainer(LispAFIConvertor.toContainer(eid)).build());
1373         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1374         mapRequestBuilder.getItrRloc().add(
1375                 new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(asIPAfiAddress(ourAddress))).build());
1376         MapRequest mr = mapRequestBuilder.build();
1377         return mr;
1378     }
1379
1380     @Test
1381     public void testNonProxy() throws SocketTimeoutException, SocketException {
1382         cleanUP();
1383         String eid = "10.0.0.1";
1384         String rloc = "127.0.0.3";
1385         MapRegister mr = createMapRegister(LispAFIConvertor.asIPAfiAddress(eid));
1386         LocatorRecord record = new LocatorRecordBuilder(mr.getEidToLocatorRecord().get(0).getLocatorRecord().get(0)).setLispAddressContainer(
1387                 LispAFIConvertor.toContainer(LispAFIConvertor.asIPAfiAddress(rloc))).build();
1388         mr.getEidToLocatorRecord().get(0).getLocatorRecord().set(0, record);
1389         sendMapRegister(mr);
1390         assertMapNotifyRecieved();
1391         MapRequest mapRequest = createMapRequest(LispAFIConvertor.asIPAfiAddress(eid));
1392         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
1393         builder.setPitr(true);
1394         mapRequest = builder.build();
1395         sendMapRequest(mapRequest);
1396         socket = new DatagramSocket(new InetSocketAddress(rloc, LispMessage.PORT_NUM));
1397         MapRequest recievedMapRequest = receiveMapRequest();
1398         assertEquals(mapRequest.getNonce(), recievedMapRequest.getNonce());
1399         assertEquals(mapRequest.getSourceEid(), recievedMapRequest.getSourceEid());
1400         assertEquals(mapRequest.getItrRloc(), recievedMapRequest.getItrRloc());
1401         assertEquals(mapRequest.getEidRecord(), recievedMapRequest.getEidRecord());
1402
1403     }
1404
1405     private void assertMapNotifyRecieved() throws SocketTimeoutException {
1406         receiveMapNotify();
1407     }
1408
1409     private MapReply receiveMapReply() throws SocketTimeoutException {
1410         return MapReplySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1411     }
1412
1413     private MapRequest receiveMapRequest() throws SocketTimeoutException {
1414         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(30000).getData()));
1415     }
1416
1417     private MapNotify receiveMapNotify() throws SocketTimeoutException {
1418         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1419     }
1420
1421     private void sendMapRequest(MapRequest mapRequest) {
1422         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array());
1423     }
1424
1425     private void sendMapRegister(MapRegister mapRegister) {
1426         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
1427     }
1428
1429     private void sendPacket(byte[] bytesToSend) {
1430         try {
1431             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
1432             initPacketAddress(packet);
1433             logger.trace("Sending MapRegister to LispPlugin on socket");
1434             socket.send(packet);
1435         } catch (Throwable t) {
1436             fail();
1437         }
1438     }
1439
1440     private DatagramPacket receivePacket() throws SocketTimeoutException {
1441         return receivePacket(6000);
1442     }
1443
1444     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
1445         try {
1446             byte[] buffer = new byte[4096];
1447             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
1448             logger.trace("Waiting for packet from socket...");
1449             socket.setSoTimeout(timeout);
1450             socket.receive(receivePacket);
1451             logger.trace("Recieved packet from socket!");
1452             return receivePacket;
1453         } catch (SocketTimeoutException ste) {
1454             throw ste;
1455         } catch (Throwable t) {
1456             fail();
1457             return null;
1458         }
1459     }
1460
1461     private void initPacketAddress(DatagramPacket packet) throws UnknownHostException {
1462         packet.setAddress(InetAddress.getByName(lispBindAddress));
1463         packet.setPort(lispPortNumber);
1464     }
1465
1466     private DatagramSocket initSocket(DatagramSocket socket) {
1467         try {
1468             socket = new DatagramSocket(new InetSocketAddress(ourAddress, LispMessage.PORT_NUM));
1469         } catch (SocketException e) {
1470             fail();
1471         }
1472         return socket;
1473     }
1474
1475     private byte[] extractWSUdpByteArray(String wiresharkHex) {
1476         final int HEADER_LEN = 42;
1477         byte[] res = new byte[1000];
1478         String[] split = wiresharkHex.split(" ");
1479         int counter = 0;
1480         for (String cur : split) {
1481             cur = cur.trim();
1482             if (cur.length() == 2) {
1483                 ++counter;
1484                 if (counter > HEADER_LEN) {
1485                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
1486                 }
1487
1488             }
1489         }
1490         return Arrays.copyOf(res, counter - HEADER_LEN);
1491     }
1492
1493     private String stateToString(int state) {
1494         switch (state) {
1495         case Bundle.ACTIVE:
1496             return "ACTIVE";
1497         case Bundle.INSTALLED:
1498             return "INSTALLED";
1499         case Bundle.RESOLVED:
1500             return "RESOLVED";
1501         case Bundle.UNINSTALLED:
1502             return "UNINSTALLED";
1503         default:
1504             return "Not CONVERTED";
1505         }
1506     }
1507
1508     @SuppressWarnings({ "rawtypes", "unchecked" })
1509     private void areWeReady() throws InvalidSyntaxException {
1510         assertNotNull(bc);
1511         boolean debugit = false;
1512         Bundle b[] = bc.getBundles();
1513         for (Bundle element : b) {
1514             int state = element.getState();
1515             logger.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v" + element.getVersion() + ", state:"
1516                     + stateToString(state));
1517             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
1518                 logger.trace("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
1519
1520                 try {
1521                     String host = element.getHeaders().get(Constants.FRAGMENT_HOST);
1522                     if (host != null) {
1523                         logger.warn("Bundle " + element.getSymbolicName() + " is a fragment which is part of: " + host);
1524                         logger.warn("Required imports are: " + element.getHeaders().get(Constants.IMPORT_PACKAGE));
1525                     } else {
1526                         element.start();
1527                     }
1528                 } catch (BundleException e) {
1529                     logger.error("BundleException:", e);
1530                     fail();
1531                 }
1532
1533                 debugit = true;
1534
1535             }
1536         }
1537         if (debugit) {
1538             logger.warn(("Do some debugging because some bundle is unresolved"));
1539         }
1540         // assertNotNull(broker);
1541
1542         int retry = 0;
1543         ServiceReference r = null;
1544         while (this.lms == null && retry < MAX_SERVICE_LOAD_RETRIES) {
1545
1546             r = bc.getServiceReference(IFlowMapping.class.getName());
1547             // r.getPropertyKeys();
1548             if (r != null) {
1549                 this.lms = (IFlowMapping) bc.getService(r);
1550             } else {
1551                 try {
1552                     Thread.sleep(1000);
1553                 } catch (InterruptedException e) {
1554                 }
1555             }
1556             retry += 1;
1557         }
1558
1559         assertNotNull(IFlowMapping.class.getName() + " service wasn't found in bundle context ", this.lms);
1560
1561         r = bc.getServiceReference(ILispDAO.class.getName());
1562         if (r != null) {
1563             this.clusterService = (ClusterDAOService) bc.getService(r);
1564         }
1565
1566         assertNotNull(ILispDAO.class.getName() + " service wasn't found in bundle context ", this.clusterService);
1567         r = bc.getServiceReference(IConfigLispPlugin.class.getName());
1568         if (r != null) {
1569             this.configLispPlugin = (IConfigLispPlugin) bc.getService(r);
1570         }
1571
1572         assertNotNull(IConfigLispPlugin.class.getName() + " service wasn't found in bundle context ", this.configLispPlugin);
1573         configLispPlugin.setLispAddress(lispBindAddress);
1574
1575         // Uncomment this code to Know which services were actually loaded to
1576         // BundleContext
1577         /*
1578          * for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
1579          * logger.trace(sr.getBundle().getSymbolicName());
1580          * logger.trace(sr.toString()); }
1581          */
1582         try {
1583             Thread.sleep(1000);
1584         } catch (InterruptedException e) {
1585         }
1586     }
1587
1588     private Ipv4 asIPAfiAddress(String ip) {
1589         return new Ipv4Builder().setIpv4Address(new Ipv4Address(ip)).setAfi((short) AddressFamilyNumberEnum.IP.getIanaCode()).build();
1590     }
1591
1592     private org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4 asPrimitiveIPAfiAddress(String ip) {
1593         return new org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Ipv4Builder()
1594                 .setIpv4Address(new Ipv4Address(ip)).setAfi((short) AddressFamilyNumberEnum.IP.getIanaCode()).build();
1595     }
1596
1597     private Mac asMacAfiAddress(String mac) {
1598         return new MacBuilder().setMacAddress(new MacAddress(mac)).setAfi((short) AddressFamilyNumberEnum.MAC.getIanaCode()).build();
1599     }
1600
1601     private org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.Mac asPrimitiveMacAfiAddress(String mac) {
1602         return new org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.MacBuilder()
1603                 .setMacAddress(new MacAddress(mac)).setAfi((short) AddressFamilyNumberEnum.MAC.getIanaCode()).build();
1604     }
1605
1606     private void cleanUP() {
1607         after();
1608         lms.clean();
1609         socket = initSocket(socket);
1610
1611     }
1612
1613 }